Force a WebView link to launch Safari?

To expand upon what Randy said, this is what I use in my application to make every http://, https://, and mailto:// URL open in the external Safari or Mail applications:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; 
{
    NSURL *requestURL =[ [ request URL ] retain ]; 
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [ [ requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ] isEqualToString: @"mailto" ]) 
        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) { 
        return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ]; 
    } 
    [ requestURL release ]; 
    return YES; 
}

As Randy says, you’ll want to implement this within whatever class you set to be the delegate of the UIWebView. To have only select URLs launch Safari, you could change their scheme from http:// to safari://, or something similar, and only kick those URLs off to the system (after replacing the custom URL scheme with http://).

I do this within my internal help documentation, which is HTML displayed in a UIWebView, so that I don’t run into issues in the review process with having a general-purpose web browser embedded in my application.

Leave a Comment