如何强制在 WebView 中单击的任何链接在 Safari 中打开? [英] How can I force any links clicked within a WebView to open in Safari?
问题描述
我的应用程序中有一个 WebView,我希望在 WebView 中单击的任何链接在 Safari 中打开(而不是 WebView 本身).
I have a WebView in my application and I would like any links clicked within the WebView to open in Safari (instead of the WebView itself).
我正在 Swift 中开发应用程序.
I am developing the application in Swift.
这样做的最佳方法是什么?
What is the best method to do this?
推荐答案
这在 Swift 中的完成方式与在 Obj-C 中的基本相同:
This is done essentially the same way in Swift as in Obj-C:
首先声明你的视图控制器符合UIWebViewDelegate
First, declare that your view controller conforms to UIWebViewDelegate
class MyViewController: UIWebViewDelegate
然后实现webViewShouldStartLoadingWithRequest:navigationType:
在你的视图控制器中:
Then implement webViewShouldStartLoadingWithRequest:navigationType:
in your View Controller:
// Swift 1 & 2
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .LinkClicked:
// Open links in Safari
UIApplication.sharedApplication().openURL(request.URL)
return false
default:
// Handle other navigation types...
return true
}
}
// Swift 3
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .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
default:
// Handle other navigation types...
return true
}
}
最后,设置您的 UIWebView
的委托,例如,在 viewDidLoad
或您的 Storyboard 中:
Finally, set your UIWebView
's delegate, e.g., in viewDidLoad
or in your Storyboard:
webView.delegate = self
这篇关于如何强制在 WebView 中单击的任何链接在 Safari 中打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!