Open Link in Safari

Here some sample code showing you how to open a link in Safari when clicked on in your UIWebView. The method shouldStartLoadWithRequest is a delegate method that is called when a link is clicked on. You can override the method and tell it to open in Safari.

- (BOOL)webView:(UIWebView *)webView
     shouldStartLoadWithRequest:(NSURLRequest *)request
     navigationType:(UIWebViewNavigationType)navigationType; {

    NSURL *requestURL = [ [ request URL ] retain ];
    // Check to see what protocol/scheme the requested URL is.
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ]
    	|| [ [ requestURL scheme ] isEqualToString: @"https" ] )
    	&& ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
        return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
   	}
    // Auto release
    [ requestURL release ];
    // If request url is something other than http or https it will open
    // in UIWebView. You could also check for the other following
    // protocols: tel, mailto and sms
    return YES;
}
 
If you like this post and would like to receive updates from this blog, please subscribe our feed. Subscribe via RSS

4 Responses to “Open Link in Safari”

  1. Julien Says:

    Hi.. I try to add this method in an UIWebViewDelegate…
    but it’s never called…

    I have miss something ?

    file MyWebView.h:
    #import
    @interface MyWebView : UIWebView {
    }
    @end

    file MyWebView.m:
    #import “MyWebView.h”
    @implementation MyWebView
    -(BOOL)shouldStartLoadWithRequest:(NSURLRequest *)request
    navigationType:(UIWebViewNavigationType)navigationType; {
    NSLog(@”call shouldStartLoadWithRequest”);

    }

  2. doug Says:

    You need to set your class as the UIWebViewDelegate. Modify MyWebView.h to look like:

    @interface MyWebView : UIWebView {

  3. andrei Says:

    Thanks for saving our time with such posts. The thing I didn’t really understand – why do you need [ [ request URL ] retain ] and [ requestURL release ]?

  4. mahnuh Says:

    hi!
    i have the same problem and i haven’t figured it out since weeks… :-(
    maybe someone can help me?
    i have a window based aplication with an UIWebView and i want http://-links to be opened in safari.
    what do i have to do?
    greetings from germany!
    mahnuh

Leave a Reply