Open links from UIWebView in MobileSafari

September 6th, 2008 Arash

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).

Comments

  1. March 21st, 2009 at 12:51 | #1

    Actually, you’ll probably never return the NO from that delegate method, as the openURL: will start a chain of events which cause your app to get shutdown as MobileSafari is started.

    But, of course, you’re doing the right thing which is to logically continue as if nothing happened out of the ordinary. I.e., you can’t assume you’ll get spirited away immediately, and, you may not, in future multi-tasking versions of the iPhone OS.

Comments are closed.