问题描述
我的应用程序中有一个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:
在您的View Controller中:
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
}
}
最后,例如在viewDidLoad
或情节提要中设置UIWebView
的委托:
Finally, set your UIWebView
's delegate, e.g., in viewDidLoad
or in your Storyboard:
webView.delegate = self
这篇关于如何强制在WebView中单击的任何链接在Safari中打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!