如何从 uitextview 中提取 link 并从 link 加载图像,如 facebook 或 twitter?
How to extract link from uitextview and load image from the link like facebook or twitter?
我想从 uitextview 中提取 link 并从 link 加载图像。例子就像这样 https://www.google.com/search?q=twitter+link&espv=2&biw=1380&bih=689&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH5I2DsbXLAhVRJI4KHXCcD-YQ_AUIBigB#tbm=isch&q=twitter+link+preview&imgrc=ID-I2bdqhuiYZM%3A 。我该怎么做?
最简单的解决方案之一是从文本视图中检测 url,如果 url 有效则加载它并提取包含文档标题和几行文本的 header从响应 body,还从返回的响应加载任何图像,并将所有这些放在一个漂亮的 UI.
中
- 将文本视图 属性 设置为:
使用 -
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
}
得到url.
查看图片
当您点击 http://www.google.com 时,委托函数 shouldInteractWithURL 将检测到 url 被点击,您将在 URL 参数中获得 url。
- 然后下载到imageview中显示。
这是代码。
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * testStr=@"The world’s most popular camera is more advanced than ever. The 12-megapixel iSight camera captures sharp, detailed photos. It takes brilliant 4K video, up to four times the resolution of 1080p HD video. http://cdn2.gsmarena.com/vv/bigpic/apple-iphone-6s1.jpg. iPhone 6s also takes selfies worthy of a self-portrait with the new 5-megapixel FaceTime HD camera. And it introduces Live Photos, a new way to relive your favourite memories. It captures the moments just before and after your picture and sets it in motion with just the press of a finger.";
[self identifyTextContent:testStr];
}
-(void)identifyTextContent :(NSString *)txtvwstr
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:txtvwstr];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
[detector enumerateMatchesInString:txtvwstr options:kNilOptions range:NSMakeRange(0, [txtvwstr length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(@"Values: %@", result);
if (result.resultType == NSTextCheckingTypeLink)
{
NSLog(@"matched: %@",result.URL);
//**You can use [SDWebImage][1] library to download the image from detected url.**//
NSData *data = [NSData dataWithContentsOfURL:result.URL];
UIImage *img = [[UIImage alloc] initWithData:data];
textAttachment.image = img;
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:result.range withAttributedString:attrStringWithImage];
}
}];
//**HERE _txtVwData is my UITextView outlet.**
_txtVwData.attributedText=attributedString;
}
希望对您有所帮助。
谢谢
这是输出屏幕。
我将答案 Payal Umraliya 转换为 swift
func imageText(text:String) {
let style = NSMutableParagraphStyle()
let myFont = UIFont(name: "roboto-Light", size: 19)
let attributedString = NSMutableAttributedString.init(string: text, attributes: [NSParagraphStyleAttributeName:style, NSFontAttributeName: myFont!])
let textAttachment = NSTextAttachment.init()
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
detector?.enumerateMatches(in: text, options: [.withoutAnchoringBounds, .reportProgress], range:NSRange.init(location: 0, length: text.characters.count), using: { (result:NSTextCheckingResult?, flag:NSRegularExpression.MatchingFlags, stop:UnsafeMutablePointer?) in
if (result?.resultType == NSTextCheckingResult.CheckingType.link) {
let data = NSData(contentsOf: (result?.url)!)
let image = UIImage.init(data: data! as Data)
textAttachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200)
textAttachment.image = image
let attributedStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: (result?.range)!, with: attributedStringWithImage)
}
})
textView.attributedText = attributedString
}
或者在一篇文章中多张照片
func imageText(text:String) {
let style = NSMutableParagraphStyle()
let myFont = UIFont(name: "roboto-Light", size: 19)
let attributedString = NSMutableAttributedString(string: text, attributes: [NSParagraphStyleAttributeName:style, NSFontAttributeName: myFont!])
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector?.matches(in: text, options: .reportCompletion, range:NSRange(location: 0, length: text.characters.count))
for match in matches! {
let textAttachment = NSTextAttachment.init()
let data = NSData(contentsOf: (match.url!))
if data != nil{
let image = UIImage(data: data! as Data)
textAttachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200)
textAttachment.image = image
let attributedStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: (match.range), with: attributedStringWithImage)
}
}
textView.attributedText = attributedString
}
Swift 已接受答案的 5.1
用法:
self.mytextView.attributedText = identifyTextContent(text_string)
函数:
func identifyTextContent(_ txtStr: String?) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: txtvwstr ?? "")
let textAttachment = NSTextAttachment()
var detector: NSDataDetector? = nil
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch {
}
detector?.enumerateMatches(in: txtvwstr ?? "", options: [], range: NSRange(location: 0, length: txtvwstr?.count ?? 0), using: { result, flags, stop in
if let result = result {
print("Values: \(result)")
}
if result?.resultType == .link {
if let URL = result?.url {
print("matched: \(URL)")
}
//// You can use any library to download the image from detected url.*/
var data: Data? = nil
if let URL = result?.url {
do {
data = try Data(contentsOf: URL)
} catch {
print(error)
}
}
var img: UIImage? = nil
if let data = data {
img = UIImage(data: data)
//// Here You can adjust image size as well using CGSize(width, height).*/
}
textAttachment.image = img
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
if let range = result?.range {
attributedString.replaceCharacters(in: range, with: attrStringWithImage)
}
}
})
return attributedString
}
我想从 uitextview 中提取 link 并从 link 加载图像。例子就像这样 https://www.google.com/search?q=twitter+link&espv=2&biw=1380&bih=689&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiH5I2DsbXLAhVRJI4KHXCcD-YQ_AUIBigB#tbm=isch&q=twitter+link+preview&imgrc=ID-I2bdqhuiYZM%3A 。我该怎么做?
最简单的解决方案之一是从文本视图中检测 url,如果 url 有效则加载它并提取包含文档标题和几行文本的 header从响应 body,还从返回的响应加载任何图像,并将所有这些放在一个漂亮的 UI.
中- 将文本视图 属性 设置为:
使用 -
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { }
得到url.
查看图片
当您点击 http://www.google.com 时,委托函数 shouldInteractWithURL 将检测到 url 被点击,您将在 URL 参数中获得 url。
- 然后下载到imageview中显示。
这是代码。
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * testStr=@"The world’s most popular camera is more advanced than ever. The 12-megapixel iSight camera captures sharp, detailed photos. It takes brilliant 4K video, up to four times the resolution of 1080p HD video. http://cdn2.gsmarena.com/vv/bigpic/apple-iphone-6s1.jpg. iPhone 6s also takes selfies worthy of a self-portrait with the new 5-megapixel FaceTime HD camera. And it introduces Live Photos, a new way to relive your favourite memories. It captures the moments just before and after your picture and sets it in motion with just the press of a finger.";
[self identifyTextContent:testStr];
}
-(void)identifyTextContent :(NSString *)txtvwstr
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:txtvwstr];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
[detector enumerateMatchesInString:txtvwstr options:kNilOptions range:NSMakeRange(0, [txtvwstr length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(@"Values: %@", result);
if (result.resultType == NSTextCheckingTypeLink)
{
NSLog(@"matched: %@",result.URL);
//**You can use [SDWebImage][1] library to download the image from detected url.**//
NSData *data = [NSData dataWithContentsOfURL:result.URL];
UIImage *img = [[UIImage alloc] initWithData:data];
textAttachment.image = img;
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:result.range withAttributedString:attrStringWithImage];
}
}];
//**HERE _txtVwData is my UITextView outlet.**
_txtVwData.attributedText=attributedString;
}
希望对您有所帮助。 谢谢
这是输出屏幕。
我将答案 Payal Umraliya
func imageText(text:String) {
let style = NSMutableParagraphStyle()
let myFont = UIFont(name: "roboto-Light", size: 19)
let attributedString = NSMutableAttributedString.init(string: text, attributes: [NSParagraphStyleAttributeName:style, NSFontAttributeName: myFont!])
let textAttachment = NSTextAttachment.init()
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
detector?.enumerateMatches(in: text, options: [.withoutAnchoringBounds, .reportProgress], range:NSRange.init(location: 0, length: text.characters.count), using: { (result:NSTextCheckingResult?, flag:NSRegularExpression.MatchingFlags, stop:UnsafeMutablePointer?) in
if (result?.resultType == NSTextCheckingResult.CheckingType.link) {
let data = NSData(contentsOf: (result?.url)!)
let image = UIImage.init(data: data! as Data)
textAttachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200)
textAttachment.image = image
let attributedStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: (result?.range)!, with: attributedStringWithImage)
}
})
textView.attributedText = attributedString
}
或者在一篇文章中多张照片
func imageText(text:String) {
let style = NSMutableParagraphStyle()
let myFont = UIFont(name: "roboto-Light", size: 19)
let attributedString = NSMutableAttributedString(string: text, attributes: [NSParagraphStyleAttributeName:style, NSFontAttributeName: myFont!])
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector?.matches(in: text, options: .reportCompletion, range:NSRange(location: 0, length: text.characters.count))
for match in matches! {
let textAttachment = NSTextAttachment.init()
let data = NSData(contentsOf: (match.url!))
if data != nil{
let image = UIImage(data: data! as Data)
textAttachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200)
textAttachment.image = image
let attributedStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: (match.range), with: attributedStringWithImage)
}
}
textView.attributedText = attributedString
}
Swift 已接受答案的 5.1
用法:
self.mytextView.attributedText = identifyTextContent(text_string)
函数:
func identifyTextContent(_ txtStr: String?) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: txtvwstr ?? "")
let textAttachment = NSTextAttachment()
var detector: NSDataDetector? = nil
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch {
}
detector?.enumerateMatches(in: txtvwstr ?? "", options: [], range: NSRange(location: 0, length: txtvwstr?.count ?? 0), using: { result, flags, stop in
if let result = result {
print("Values: \(result)")
}
if result?.resultType == .link {
if let URL = result?.url {
print("matched: \(URL)")
}
//// You can use any library to download the image from detected url.*/
var data: Data? = nil
if let URL = result?.url {
do {
data = try Data(contentsOf: URL)
} catch {
print(error)
}
}
var img: UIImage? = nil
if let data = data {
img = UIImage(data: data)
//// Here You can adjust image size as well using CGSize(width, height).*/
}
textAttachment.image = img
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
if let range = result?.range {
attributedString.replaceCharacters(in: range, with: attrStringWithImage)
}
}
})
return attributedString
}