从iOS应用程序在浏览器中打开超链接

时间:2017-07-09 12:52:03

标签: ios swift

我是iOS开发的新手。我创建了一个带有超链接的基本html页面。我使用以下代码将html页面转换为app。

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var lupView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        lupView.loadRequest(URLRequest(url: Bundle.main.url(forResource: "lup_package/lup/index", withExtension: "html")!))


    }

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


}

当我将它构建到iPad Air时,一切正常。但是当我点击超链接时,目标网站就会在应用程序中打开。我希望在浏览器中打开它。请帮助我实现这一点,如果你解释我的工作会很好。

1 个答案:

答案 0 :(得分:2)

如果您只是想使用Safari打开网址,以下内容应该有所帮助。

if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url, options: [:])
}

如果您想使用Safari在WebView上打开超链接。检查this。您需要使用webView:shouldStartLoadWith委托方法。请记住在视图控制器或故事板中设置lupView.delegate = self

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

        if navigationType == .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
        }

        // Handle other navigation types...
        return true
    }