0

I have an iOS app using Swift 3. I have a uiwebview in this app. Whenever a user clicks on a link in the webview, it opens up inside the webview. I need it to where the links open up inside the Safari app on the iPhone. Here's the code:

class VideosViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        var URL = NSURL(string: "http://example.com")

        webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)


    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Can you please give me some code that I can enter? I'm new at coding, so thanks a lot.

UPDATE: Thanks to an answer I got some code, but the links are still not opening in Safari. Here's the code so far...

class VideosViewController : UIViewController, UIWebViewDelegate {

@IBOutlet weak var webView : UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    guard let url = URL(string: "http://example.com") else { return }

    let request = URLRequest(url: url)
    webView.loadRequest(request)

}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    if navigationType == .linkClicked {

        guard let url = request.url else { return true }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
        return false
    }
    return true
}

}

1 Answer 1

1

Using UIWebView:

Make sure your view controller conforms to UIWebViewDelegate and then implement this method in the controller:

class VideosViewController : UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView : UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let url = URL(string: "http://example.com") else { return }
        
        webView.delegate = self

        let request = URLRequest(url: url)
        webView.loadRequest(request)

    }

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

Using WKWebView:

Use a WKWebView instead of a UIWebView and make sure your controller conforms to the WKNavigationDelegate protocol. So your implementation would look something like the following:

class VideosViewController : UIViewController, WKNavigationDelegate {

    var webView : WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        guard let url = URL(string: "http://example.com") else { return }
    
        webView = WKWebView(frame: self.view.frame)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.isUserInteractionEnabled = true
        webView.navigationDelegate = self
    
        self.view.addSubview(self.webView)
    
        let request = URLRequest(url: url)
        webView.load(request)
    
    }


    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    
        // Check if a link was clicked
        if navigationAction.navigationType == .linkActivated {
        
            // Verify the url
            guard let url = navigationAction.request.url else { return }
            let shared = UIApplication.shared
        
            // Check if opening in Safari is allowd
            if shared.canOpenURL(url) {
            
                // Ask the user if they would like to open link in Safari
                let alert = UIAlertController(title: "Open link in Safari?", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
                    // User wants to open in Safari
                    shared.open(url, options: [:], completionHandler: nil)
                }))
                alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
            
                present(alert, animated: true, completion: nil)
            
            }
            decisionHandler(.cancel)
        }
        decisionHandler(.allow)
    }
}

This way, when a user clicks a link in the web view, they will be prompted with an alert that will ask them whether or not they would like to open it in Safari, and if it is allowed, Safari will launch and the link will be opened.

13
  • I'm getting an error saying "Missing argument for parameter 'mimeType" in call" on the webView.load(request) Nov 25, 2016 at 12:13
  • If you are using Swift 3 and you entered the code that I did that should work, I've repeatedly tested it myself.
    – Wes
    Nov 25, 2016 at 20:12
  • Thanks Wes, the WKWebView works, but the UIWebView does not because of what I said earlier... Nov 26, 2016 at 18:20
  • Would you mind editing your question to show all pertinent parts of your View Controller as they look now?
    – Wes
    Nov 26, 2016 at 19:28
  • Thats an entirely different issue. If it worked for you, please accept the answer to this question and start a new one.
    – Wes
    Nov 27, 2016 at 1:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.