How to get the first image URL from NSString ?

by Kishore on July 11, 2011

I am working on a RSS feed reader and I need to get the first image URL from the feed post. A simple function to get the first image URL from the HTML contents.
- (NSString *)getFirstImageUrl: (NSString *) html {
    NSString *tempText = [[NSString alloc]initWithFormat:@""];
    NSScanner * pageScanner = [NSScanner scannerWithString:html];
    [pageScanner setCaseSensitive:NO];
    [pageScanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [pageScanner scanUpToString:@"<img " intoString:nil];
    [pageScanner scanString:@"<img " intoString:nil];
    [pageScanner scanUpToString:@"src="" intoString:nil];
    [pageScanner scanString:@"src="" intoString:nil];
    [pageScanner scanUpToString:@""" intoString:&tempText];
    return tempText;
}

You can even get all the images in an NSMutable Array using a loop.

Update : July 11, 2011, 7:22 am

I have not used [tempText Release] or any other release as this code is with iOS 5 where you do not need to manage memory manually.

  1. How to get the current URL of web page in PHP : A simple function that I had...
  2. Shorten Long URL using Google Short URL service : There are many URL shortening services...
  3. Create multiple 125 x 125 Image Ads for your blog using Google Ad Manager : I just finished setting up my...
  4. PHP Script to Validate URL : I have been working to create...
  5. Modifying Image size for the home page – WordPress : I have done some modification for...