WKWebView 在 safari 中打开来自特定域的链接
WKWebView open links from certain domain in safari
在我的应用程序中,我想在 WKWebView 中打开来自 my 域(例如:communionchapelefca.org)的链接,然后有来自 other 的链接 个域在 Safari 中打开。我更愿意以编程方式执行此操作。
我找到了一些关于 Stack overflow (here, here, here, and here) 的解决方案,但它们似乎都是基于 Obj-C 的,我正在寻找使用 Swift.
的解决方案
ViewController.swift:
import UIKit
import 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)
制作一个函数来决定在哪里加载 URL:
func loadURLString(str: String) {
guard let url = NSURL(string: str) else {
return
}
if url.host == "www.communionchapelefca.org" {
// Open in myWebView
myWebView.loadRequest(NSURLRequest(URL: url))
} else {
// Open in Safari
UIApplication.sharedApplication().openURL(url)
}
}
用法:
loadURLString("http://www.communionchapelefca.org/app-home") // Open in myWebView
loadURLString("http://www.apple.com") // Open in Safari
您可以实施 WKNavigationDelegate
,添加 decidePolicyForNavigationAction
方法并检查导航类型并请求 url。我在下面使用了 google.com,但您可以将其更改为您的域:
Xcode 8.3 • Swift 3.1 或更高版本
import UIKit
import 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)
return
} else {
print("Open it locally")
decisionHandler(.allow)
return
}
} else {
print("not a user click")
decisionHandler(.allow)
return
}
}
}
对于Swift3.0
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
let wv = WKWebView(frame: UIScreen.main.bounds)
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "https://www.google.com") else { return }
wv.navigationDelegate = self
wv.load(NSURLRequest(url: url as URL) as URLRequest)
view.addSubview(wv)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.url,
let host = newURL.host , !host.hasPrefix("www.google.com") &&
UIApplication.shared.canOpenURL(newURL) &&
UIApplication.shared.openURL(newURL) {
print(newURL)
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)
}
}
}
这是对用 obj c 编写的 swift 的响应的示例代码。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler
{
if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
if (navigationAction.request.URL) {
NSLog(@"%@", navigationAction.request.URL.host);
if (![navigationAction.request.URL.resourceSpecifier containsString:@"ex path"]) {
if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
decisionHandler(WKNavigationActionPolicyCancel);
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
我的swift3 解决方案:
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
if url?.description.lowercased().range(of: "http://") != nil || url?.description.lowercased().range(of: "https://") != nil {
decisionHandler(.cancel)
UIApplication.shared.openURL(url!)
} else {
decisionHandler(.allow)
}
}
别忘了设置委托
public override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
Swift 4 George Vardikos 的回答更新:
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
guard url != nil else {
decisionHandler(.allow)
return
}
if url!.description.lowercased().starts(with: "http://") ||
url!.description.lowercased().starts(with: "https://") {
decisionHandler(.cancel)
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
} else {
decisionHandler(.allow)
}
}
Swift 5 和 iOS >10
不要使用 UIApplication.shared.openURL(url!)
, it's deprecated. We use UIApplication.shared.open(url!)
。
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else{
decisionHandler(.allow)
return
}
let urlString = url.absoluteString.lowercased()
if urlString.starts(with: "http://") || urlString.starts(with: "https://") {
decisionHandler(.cancel)
UIApplication.shared.open(url, options: [:])
} else {
decisionHandler(.allow)
}
}
在我的应用程序中,我想在 WKWebView 中打开来自 my 域(例如:communionchapelefca.org)的链接,然后有来自 other 的链接 个域在 Safari 中打开。我更愿意以编程方式执行此操作。
我找到了一些关于 Stack overflow (here, here, here, and here) 的解决方案,但它们似乎都是基于 Obj-C 的,我正在寻找使用 Swift.
的解决方案ViewController.swift:
import UIKit
import 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)
制作一个函数来决定在哪里加载 URL:
func loadURLString(str: String) {
guard let url = NSURL(string: str) else {
return
}
if url.host == "www.communionchapelefca.org" {
// Open in myWebView
myWebView.loadRequest(NSURLRequest(URL: url))
} else {
// Open in Safari
UIApplication.sharedApplication().openURL(url)
}
}
用法:
loadURLString("http://www.communionchapelefca.org/app-home") // Open in myWebView
loadURLString("http://www.apple.com") // Open in Safari
您可以实施 WKNavigationDelegate
,添加 decidePolicyForNavigationAction
方法并检查导航类型并请求 url。我在下面使用了 google.com,但您可以将其更改为您的域:
Xcode 8.3 • Swift 3.1 或更高版本
import UIKit
import 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)
return
} else {
print("Open it locally")
decisionHandler(.allow)
return
}
} else {
print("not a user click")
decisionHandler(.allow)
return
}
}
}
对于Swift3.0
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
let wv = WKWebView(frame: UIScreen.main.bounds)
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "https://www.google.com") else { return }
wv.navigationDelegate = self
wv.load(NSURLRequest(url: url as URL) as URLRequest)
view.addSubview(wv)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.url,
let host = newURL.host , !host.hasPrefix("www.google.com") &&
UIApplication.shared.canOpenURL(newURL) &&
UIApplication.shared.openURL(newURL) {
print(newURL)
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)
}
}
}
这是对用 obj c 编写的 swift 的响应的示例代码。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler
{
if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
if (navigationAction.request.URL) {
NSLog(@"%@", navigationAction.request.URL.host);
if (![navigationAction.request.URL.resourceSpecifier containsString:@"ex path"]) {
if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
decisionHandler(WKNavigationActionPolicyCancel);
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
我的swift3 解决方案:
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
if url?.description.lowercased().range(of: "http://") != nil || url?.description.lowercased().range(of: "https://") != nil {
decisionHandler(.cancel)
UIApplication.shared.openURL(url!)
} else {
decisionHandler(.allow)
}
}
别忘了设置委托
public override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
Swift 4 George Vardikos 的回答更新:
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
guard url != nil else {
decisionHandler(.allow)
return
}
if url!.description.lowercased().starts(with: "http://") ||
url!.description.lowercased().starts(with: "https://") {
decisionHandler(.cancel)
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
} else {
decisionHandler(.allow)
}
}
Swift 5 和 iOS >10
不要使用 UIApplication.shared.openURL(url!)
, it's deprecated. We use UIApplication.shared.open(url!)
。
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else{
decisionHandler(.allow)
return
}
let urlString = url.absoluteString.lowercased()
if urlString.starts(with: "http://") || urlString.starts(with: "https://") {
decisionHandler(.cancel)
UIApplication.shared.open(url, options: [:])
} else {
decisionHandler(.allow)
}
}