Reputation:
I would like extract the link from uitextview and load image from the link . Example would be like this 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 . How can i do it ?
Upvotes: 2
Views: 2664
Reputation: 1257
Swift 5.1 of accepted answer
Usage:
self.mytextView.attributedText = identifyTextContent(text_string)
Function:
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
}
Upvotes: 0
Reputation: 233
I convert the answer Payal Umraliya https://stackoverflow.com/a/35909188/8070211 to 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
}
Or for several photos in one text
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
}
Upvotes: 2
Reputation: 627
Here is the code.
- (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;
}
Hope this will help you. Thanks.
Here is the output screen.
Upvotes: 6
Reputation: 961
Use -
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
}
to get url.
when you click on http://www.google.com then delegate function shouldInteractWithURL will detect the url clicked you will get the url in URL parameter.
Upvotes: 2
Reputation: 261
One of the simplest solution is to detect url from text view, and if url is valid then load it and extract header containing document title and a few lines of text from response body, also load any image from returned response and put all this together in a nice UI.
Upvotes: 0