I think Regular Expressions will help.
//NSError will handle errors
NSError *error;
//Create URL for you page. http://example.com/index.php just an example
NSURL *pageURL = [NSURL URLWithString:@"http://example.com/index.php"];
//Retrive page code to parse it using regex
NSString *pageHtml = [NSString stringWithContentsOfURL:pageURL
encoding:NSUTF8StringEncoding
error:&error];
if (error)
{
NSLog(@"Error during retrieving page HTML: %@", error);
//Will terminate your app
abort();
//TODO: handle connection error here
}
error = nil;
//Creating regex to parsing page html
//Information about regex patters you can easily find.
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"<a[^>]*href=\"([^\"]*)\"[^>]*>mylink</a>"
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error)
{
NSLog(@"Error during creating regex: %@", error);
//Will terminate your app
abort();
//TODO: handle regex error here
}
//Retrieving first match of our regex to extract first group
NSTextCheckingResult *match = [regex firstMatchInString:pageHtml
options:0
range:NSMakeRange(0, [pageHtml length])];
NSString *pageUrl = [pageHtml substringWithRange:[match rangeAtIndex:1]];
NSLog(@"Page URL = %@", pageUrl);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pageUrl]]];
If your UIWebView
already downloaded page with HTML you can replace
NSURL *pageURL = [NSURL URLWithString:@"http://example.com/index.php"];
NSString *pageHtml = [NSString stringWithContentsOfURL:pageURL encoding:NSUTF8StringEncoding error:&error];
with this:
NSString *pageHtml = [webview stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];