Supertecnoboff
Supertecnoboff

Reputation: 6606

Parse <img src> tag in JSON - iOS

I have an iOS app which downloads a JSON feed. I have managed to parse everything just fine apart from one element left, which is the images.

The JSON feed I am downloading is from a PHP script online which converts certain RSS feeds to JSON. Thus why there are HTML image tags in one of the elements of the JSON feed which contains the images.

I am using the following code to access things like titles, dates, link URLS, etc... and it works great:

NSArray *titles = [[[[data_dict objectForKey:@"rss"] valueForKey:@"channel"] valueForKey:@"item"] valueForKey:@"title"];

As you can see from my code above, the titles are stored in the JSON tag called "title". Very easy to parse. The images are stored in a tag called "description".

How this tag also contains text as well as image URLS. So how can I parse the <img src> tags from it?

Here is one of the JSON description tags:

enter image description here

How can I go about parse the image links in an array?

Thanks for your time, Dan

Upvotes: 0

Views: 905

Answers (1)

Santu C
Santu C

Reputation: 2654

Please try with below code -

NSString *yourHTMLSourceCodeString = @"";

    NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

[regex enumerateMatchesInString:yourHTMLSourceCodeString
                        options:0
                          range:NSMakeRange(0, [yourHTMLSourceCodeString length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

                         NSString *img = [yourHTMLSourceCodeString substringWithRange:[result rangeAtIndex:2]];

                         NSURL *candidateURL = [NSURL URLWithString:img];

                         if (candidateURL && candidateURL.scheme && candidateURL.host)
                         {
                             NSLog(@"img src %@",img);
                         }


                     }];

Update Same thing can be done using below regex change -

 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"]((http|https)://.*?)['\"][\\s\\S]*?>)+?"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

Upvotes: 1

Related Questions