Reputation: 3078
I am trying to get the image from this website, but I am having a hard time. All I need is the URL of the image, when I print the URL I get noting back. This is the URL and I am trying to get the main image seen in the middle, http://theoldrussuanbum.vsco.co/media/555722fde555153e3e8b4591
I have been trying the following code with no luck.
NSURL *URL = [NSURL URLWithString:_urlTextField.text];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:URL completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *contentType = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields];
contentType = headers[@"Content-Type"];
}
HTMLDocument *document = [HTMLDocument documentWithData:data
contentTypeHeader:contentType];
HTMLElement *element = [document firstNodeMatchingSelector:@"img"];
NSString *urlString = element.attributes[@"src"];
NSLog(@"URL: %@", urlString);
}] resume];
Can anyone help?
Upvotes: 0
Views: 720
Reputation: 112875
You can use regular expressions to first
find the start with the regular expression: @"twitter:image\"\\s+content=\""
and then
extract the URL with the regular expression: @"[^>]+"
You can find information of regular expression syntax at the ICU User Guide: Regular Expressions.
Example code:
NSString *urlString = @"http://theoldrussuanbum.vsco.co/media/555722fde555153e3e8b4591";
NSURL *URL = [NSURL URLWithString:urlString];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *sessionTask;
sessionTask = [session dataTaskWithURL:URL completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange preambleRange = [html rangeOfString:@"twitter:image\"\\s+content=\"" options:NSRegularExpressionSearch];
if (preambleRange.location != NSNotFound) {
NSString *htmlOffset = [html substringFromIndex:preambleRange.location + preambleRange.length];
NSRange imgUrlRange = [htmlOffset rangeOfString:@"[^>]+" options:NSRegularExpressionSearch];
if (imgUrlRange.location != NSNotFound) {
NSString *imgURLString = [htmlOffset substringWithRange:imgUrlRange];
NSLog(@"URL: %@", imgURLString);
}
}
}];
[sessionTask resume];
Output:
URL: http://image.vsco.co/1/548c6a64020e11517164/555722fde555153e3e8b4591/600x800/vsco_051615.jpg"
Of course production code must handle all errors which this example code does not.
Upvotes: 3
Reputation: 898
I think first thing you need to do is provide actual url of image resource.
For example; http://image.vsco.co/1/548c6a64020e11517164/548c7b532b5615b6658b4567/vsco_121314.jpg
This is what I get from page source of that web page
And then just refer this question;
iOS download and save image inside app
Upvotes: 0