Open specific link in Safari from UIWebView

♀尐吖头ヾ 提交于 2019-12-21 21:49:38

问题


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
    }


来源:https://stackoverflow.com/questions/34741403/open-specific-link-in-safari-from-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!