-
Getting the first HTML image URL from a string in Objective-C
@MatthewSaeger came to me the other day with the following question -
“How do I get the first image from a string I’m retrieving via the iPhone’s XML Parser?”
The answer is actually really simple. It can be done via regex, but for simplicity’s sake, doing a simple string replacement does the trick quite nicely. Here, take a look for yourself.
The original string looks a little something like this after the XML Parser is completed
The first part is really simple, we must first split the string wherever the first “src=” occurs -NSArray *splitonce = [theDescription componentsSeparatedByString:@"src=\""];
The final splitting occurs at the first occurrence of the double quote character (“), since that’s where the src attribute would end in the HTML tag.NSString *finalSplitString = [[NSString alloc] initWithString:[splitonce objectAtIndex:1]];
NSArray *finalSplit = [finalSplitString componentsSeparatedByString:@"\""];
The final image URL that we’re looking for is in the first key of the finalSplit array. If we NSLog(); the string, we’ll see what we are looking for.NSString *imageURL = [[NSString alloc] initWithString:[finalSplit objectAtIndex:0]];
imageURL = [imageURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"%@", imageURL);
Here’s what you’ll see in the Debugger Console =)