How can I make any links within a webview open in safari in Xcode?

3 Solutions Collect From Internet About “How can I make any links within a webview open in safari in Xcode?”

This is done essentially the same way in Swift as in Obj-C:

First, declare that your view controller conforms to UIWebViewDelegate

class MyViewController: UIWebViewDelegate

Then implement webViewShouldStartLoadingWithRequest:navigationType: in your View Controller:

// Swift 1 & 2
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    switch navigationType {
    case .LinkClicked:
        // Open links in Safari
        UIApplication.sharedApplication().openURL(request.URL)
        return false
    default:
        // Handle other navigation types...
        return true
    }
}

// Swift 3
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    switch navigationType {
    case .linkClicked:
        // Open links in Safari
        guard let url = request.url else { return true }

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            // openURL(_:) is deprecated in iOS 10+.
            UIApplication.shared.openURL(url)
        }
        return false
    default:
        // Handle other navigation types...
        return true
    }
}

Finally, set your UIWebView‘s delegate, e.g., in viewDidLoad or in your Storyboard:

webView.delegate = self

Updated for swift 3

func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.linkClicked {
        UIApplication.shared.open(shouldStartLoadWith.url!, options: [:], completionHandler: nil)
        return false
    }
    return true
}

You need to implement the method webViewShouldStartLoadingWithRequest:navigationType on your web view’s delegate and look for the links you want to open in Safari. If you send those off to the OS with [[UIApplication sharedApplication]openURL:] they will open in Safari.