Open links from UIWebView in MobileSafari

September 6th, 2008 Arash Posted in Tutorials, iPhone |

If you’ve embedded a UIWebView in your iPhone/iPod app, you may not want the user to suffer through surfing all successive pages through it. Instead, you can open up your first page inside a UIWebView and any links the user tries to follow will instead open up in MobileSafari.

All you need to do is set the UIWebView’s delegate, to an object that implements the optional method webView:shouldStartLoadWithRequest:navigationType: (part of the UIWebViewDelegate protocol). Then whenever the initial page is loaded or a link is followed in that view, the delegate’s method will be called. You’ll want to return YES for the page you initially load, and then return NO for all others, and open the URL in MobileSafari. Here’s what the method implementation should look like:

- (BOOL)webView:(UIWebView *)webView
    shouldStartLoadWithRequest:(NSURLRequest *)request
    navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] absoluteString] isEqual:@"http://arashpayan.com/myInitialPage/"])
        return YES;
    
    [[UIApplication sharedApplication] openURL:[request URL]];
    
    return NO;
}

By returning NO from the delegate method, we’re telling the web view not to load the link the user tapped, but instead we redirect the opening of the link to [UIApplication openURL:] (MobileSafari).

Leave a Reply