Force a WebView link to launch Safari?

前端 未结 5 2049
广开言路
广开言路 2020-12-04 08:28

I have a UIWebView embedded within an iPhone app of mine. I want to be able to have certain links within that webview open into the full Mobile Safari app (i.e. not my embed

5条回答
  •  无人及你
    2020-12-04 09:05

    I haven't tried this myself but I think that you can implement the UIWebViewDelegate method

    webView:shouldStartLoadWithRequest:navigationType 
    

    which will be called anytime a link in the UIWebView is clicked on. In that method you just need to determine if the clicked link should result in launching Safari or not and use openURL if it should.

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        // Check if this was a click event and then some other criteria for determining if you want to launch Safari.
        if (navigationType == UIWebViewNavigationTypeLinkClicked && [Some other criteria]) {
            [[UIApplication sharedApplication] openURL:request.URL];
    
            // Return false to indicate to the UIWebView to not navigate to the linked target
            return false;
        }
    
        // Return true so that the UIWebView loads the link target
        return true;
    }
    

    Don't forget that you need to set your UIWebView delegate property to an instance of the class that implements the UIWebViewDelegate.

提交回复
热议问题