Nick Harris

Finding a FavIcon URL

with one comment

Being relatively new to objective-c, I was wondering what people thought of this code. The idea was to find the favIcon URL from a string of HTML. Is this the fastest/most efficient way without using RegEx?

-(NSString*)favIconUrlStringFromHtmlString:(NSString*)htmlString

{

NSScanner *htmlScanner = [NSScanner scannerWithString:htmlString];

while ([htmlScanner isAtEnd] == NO)

{

[htmlScanner scanUpToString:@"<link" intoString:NULL];

if(![htmlScanner isAtEnd])

{

NSString *linkString;

[htmlScanner scanUpToString:@"/>" intoString:&linkString];

// we have a link element.  does it have rel set to anything we want?

if(([linkString rangeOfString:@"rel=\"shortcut icon\""].location != NSNotFound)||

  ([linkString rangeOfString:@"rel='shortcut icon'"].location != NSNotFound)||

  ([linkString rangeOfString:@"rel=\"icon\""].location != NSNotFound)||

  ([linkString rangeOfString:@"rel='icon'"].location != NSNotFound)||

  ([linkString rangeOfString:@"rel=icon "].location != NSNotFound))

{

// yep, grab the href

NSScanner *hrefScanner = [NSScanner scannerWithString:linkString];

[hrefScanner scanUpToString:@"href=" intoString:NULL];

if(![hrefScanner isAtEnd])

{

[hrefScanner scanString:@"href=" intoString:NULL];

NSString *hrefString;

// scan up to a space. 

// if we don't hit one cause the href was the last thing in the element, we don't care

[hrefScanner scanUpToString:@" " intoString:&hrefString];

// clean up any quotes

hrefString = [hrefString stringByReplacingOccurrencesOfString:@"\"" withString:@""];

hrefString = [hrefString stringByReplacingOccurrencesOfString:@"'" withString:@""];

// we're done, return

return hrefString;

}

}

}

}

return nil;

}

Advertisements

Written by Nick Harris

March 24, 2010 at 10:11 pm

Posted in Uncategorized

One Response

Subscribe to comments with RSS.

  1. Don’t know if this is the most efficient way of doing it. But you shouldn’t look for “/>” but for “>” to get the link element.

    Titouan Van Belle

    January 12, 2012 at 2:54 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: