crossboy007 crossboy007 - 1 month ago 11
iOS Question

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

I have a webview in my application and I would like any links in the web view to open in safari instead of the web view itself.

I am coding the application in swift, and have seen some answers for objective-c but none for swift.

Does anybody know how I can go about doing this?

Answer

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:

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
    }
}

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

webView.delegate = self