Search code examples
htmlobjective-cxcodeimagefinder

Scan for images in website - Xcode


I am making an app which will give me the latest news, and the image. I achieve the text bit by making a scanner like this.

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    /* set headers, etc. on request if needed */
    [request setURL:[NSURL URLWithString:@"http://stackoverflow.com/questions/22671347/nsuinteger-should-not-be-used-in-format-strings"]];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSScanner *scanner = [NSScanner scannerWithString:html];
    NSString *token = nil;
    [scanner scanUpToString:@"<p>" intoString:NULL];
    [scanner scanUpToString:@"</p>" intoString:&token];
    int length = 3;


   token = [token substringFromIndex:length];
    textView.text = token;

Now I was wondering if I could use the same type of code to scan the website to find the first image and put it an image view. Also it don't have to be same type of code , post what ever you know and any method.

Summary is.

Want a piece of code that will scan a webpage, pick up the first image and place it in a image view.

Thanks for the people who take the time to help me.

THANKS AGAIN!!! BYE!!!


Solution

  • NSScanner its not a HTML parser only intended for scanning values from NSString object. If you doing the odd scan you probably could get away with it, but it doesn't seem like...

    The CORRECT approach is to use Libxml2 library included in Xcode which is only written is C which doesn't have any Objective-C/Swift wrapper. Libxml2 is the XML C parser and toolkit developed for the Gnome project. Alternatively i would recommend using open-source project such as HTMLReader. Its a HTML parser with CSS selectors in Objective-C and Foundation. It parses HTML just like a browser and is all written in Objective-c.

    Example (using HTMLReader):

    HTMLDocument *document = [HTMLDocument documentWithString:html]; // get your html string
    NSLog(@"IMG: %@", [document firstNodeMatchingSelector:@"img"].textContent); // => image returned here
    

    To find images just change the tag to < img > and your set!!

    IF your using Libxml2 take a look at HTMLparser.c header file to parse and retrieve HTML ltags