2010-01-28

IPhone: Open a link into Safari from within web view

Here is the situation:
You have an application in which you use web view to show some content. The client decides that he wants marketing materials, so they provide you with HTML containing links. How do you prevent the web view of loading this links into your app, and force safari to open ?


The answer is - add this method to your web view delegate:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request


 navigationType:(UIWebViewNavigationType)navigationType {
    // if the new content is due to click on a link
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        // standard way to launch external app, in this case safari
        [[UIApplication sharedApplication] openURL:request.URL];
        
        // tell the web view that we have handle it, so it should stop loading
        return false;
    }
    
    // otherwise, tell the web view to load the content
    return true;
}


No comments:

Post a Comment