2 image hyperlink uitextview ios swift
我想从 uitextview 中提取链接并从链接中加载图像。示例将是这样的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=1389 -I2bdqhuiYZM%3A。我该怎么做 ?
这是代码。
- (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;
}
Run Code Online (Sandbox Code Playgroud)
希望这会帮助你。谢谢。
这是输出屏幕。