Proud Member
Proud Member

Reputation: 40496

How to launch links in UIWebView with the Safari app?

I have an small embedded UIWebView for my about-section of the app. When the user taps a link in there, the link opens in that small embedded UIWebView which of course has no navigation controls and isn't full-screen. I don't like that. Can I force it to open links with Safari instead?

Upvotes: 0

Views: 963

Answers (2)

Sheepdogsheep
Sheepdogsheep

Reputation: 417

You should implement shouldStartLoadWithRequest of the UIWebViewDelegate. In here you can see when the UIWebView will start loading a URL. Then you can handle which should be loaded in this webView and which should be loaded by Safari.

My code looks like:

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType 
{
    if (inType != UIWebViewNavigationTypeLinkClicked)
    {
        //This was not a clicked link, so is probably the initial load 
        //and should be loaded in the UIWebView
        return YES;
    }

    //This was a clicked link, so load using Safari
    [[UIApplication sharedApplication] openURL:[inRequest URL]];

    return NO;
}

Here I am using UIWebViewNavigationType to determine whether it was a link click, and responding appropriately.

Upvotes: 0

codelark
codelark

Reputation: 12334

You can implement the shouldStartLoadWithRequest method of the UIWebViewDelegate protocol to intercept link clicks. Inside that method you can use UIApplication's openURL method to cause the url to be opened in the appropriate application (ie. Safari for HTTP/HTTPS).

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];

    if ([url isEqual:YOUR_HOME_URL_CONTSTANT])
        return YES;

    [[UIApplication sharedApplication] openURL:url];

    return NO;
}

Upvotes: 2

Related Questions