crossboy007 crossboy007 - 5 months ago 49
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?


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
        return false
        // Handle other navigation types...
        return true

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

webView.delegate = self