WKWebView在Safari中打开来自某些域的链接
在我的应用程序中,我想在WKWebView中从 我的 域(例如:communionchapelefca.org)内打开链接,然后在Safari中打开来自
其他 域(例如:google.com)的链接。我希望以编程方式执行此操作。
我已经找到了一些关于Stack溢出的解决方案,但是它们似乎都是基于Obj-C的,我正在寻找使用Swift的解决方案。
ViewController.swift:
import UIKitimport WebKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myWebView:WKWebView = WKWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.communionchapelefca.org/app-home")!))
self.view.addSubview(myWebView)
回答:
您可以实现WKNavigationDelegate
,添加decidePolicyForNavigationAction
方法,然后在其中检查navigationType和所请求的url。我在下面使用了
**google.com** ,但您可以将其更改为您的域:
import UIKitimport WebKit
class ViewController: UIViewController, WKNavigationDelegate {
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = view.bounds
webView.navigationDelegate = self
let url = URL(string: "https://www.google.com")!
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url,
let host = url.host, !host.hasPrefix("www.google.com"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
print(url)
print("Redirected to browser. No need to open it locally")
decisionHandler(.cancel)
} else {
print("Open it locally")
decisionHandler(.allow)
}
} else {
print("not a user click")
decisionHandler(.allow)
}
}
}
以上是 WKWebView在Safari中打开来自某些域的链接 的全部内容, 来源链接: utcz.com/qa/406564.html