Reputation: 111
I am trying to extract the URL for an image from a string of text. It may be from different websites, and could be any form of image (jpg, png, gif, etc.). What would be a good way to scan the string, find any matching picture extension, and get the graphic from it?
The string may be something like this:
Hello, I hope you like my picture located at http://www.website.com/picture1.png. However, if you don't, I know you'll like this one http://www.website2.org/picture2.jpg.Please refer all comments to http://www.website5.com/
I want to be able to scan the string for ONLY URLs of image files, and make a new string of whatever the first image URL is. So in this string, I could create a new string that only has http://www.website.com/picture1.png
Upvotes: 1
Views: 816
Reputation: 85
Use below code after later finish with @Anup Kumar
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL *url = [match URL];
} else if ([match resultType] == NSTextCheckingTypePhoneNumber) {
NSString *phoneNumber = [match phoneNumber];
}
}
Upvotes: 1
Reputation: 399
Well, to get the extension you can use the NSString method pathExtension, this will result in a string with just the extension, so you will know if it is jpg, gif, png, etc.
NSString* path = @"http://location.com/pictures/image.jpg";
NSString* extension = [path pathExtension];
For your graphic you can use the UIImage imageWithData method, and pass it the output from NSData dataWithContentsOfUrl method, using these methods together will allow you to create a UIImage which you can then display in a UIImageView.
UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:path]];
Hopefully that is helpful.
Upvotes: 0
Reputation:
I got from The Link Objective-C - Finding a URL within a string
No need to use RegexKitLite
for this, since iOS 4 Apple provide NSDataDetector
(a subclass of NSRegularExpression
).
You can use it simply like this (source is your string) :
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:source options:0 range:NSMakeRange(0, [source length])];
Upvotes: 5