Open specific link in Safari from UIWebView

2020-07-26 11:35发布

问题:

I have a UIWebView which loads a local index.html file.

However I have an external link in this html file that I'd like to open in Safari instead of internally in the UIWebView.

Opening a link in safari from say a UIButton was simple enough:

UIApplication.sharedApplication().openURL(NSURL(string: "http://www.stackoverflow.com"))

Opening the Instagram app from a external link also works like a charm.

<a href="instagram://media?id=434784289393782000_15903882">instagram://media?id=434784289393782000_15903882</a>

So my first though was to do something like this:

<a href="safari://stackoverflow.com">Open in Safari</a>

However that doesn't seem to work, then I read something about using webView:shouldStartLoadWithRequest:navigationType:

But everyone who's managed to open an external link in Safari is writing in Obj-C which I'm not too familiar with as I'm writing in Swift.

Update with Swift Code:

import UIKit

class AccessoriesViewController: UIViewController, UIWebViewDelegate {


    @IBOutlet weak var webView:UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()


        if let url = NSBundle.mainBundle().URLForResource("accessories", withExtension: "html") {
            webView.loadRequest(NSURLRequest(URL: url))
        }



    }
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.LightContent;
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(url)
            return false
        }
        return true
    }

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


}

回答1:

Here is how you can do it!

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(url)
            return false
        }
        return true
    }