如何在Xcode中的safari中打开webview中的任何链接? [英] How can I make any links within a webview open in safari in Xcode?
问题描述
我的应用程序中有一个webview,我希望Web视图中的任何链接都可以在safari中打开,而不是在Web视图中打开。
I have a webview in my application and I would like any links in the web view to open in safari instead of the web view itself.
我正在编码应用程序在swift中,并且已经看到了objective-c的一些答案,但没有看到swift的答案。
I am coding the application in swift, and have seen some answers for objective-c but none for swift.
有人知道我该怎么做吗?
Does anybody know how I can go about doing 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中的c $ c>
:
// 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
或在你的故事板中:
Finally, set your UIWebView
's delegate, e.g., in viewDidLoad
or in your Storyboard:
webView.delegate = self
这篇关于如何在Xcode中的safari中打开webview中的任何链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!