ios swift safari wkwebview

ios - WKWebView abre enlaces de cierto dominio en safari



swift (7)

Actualización de Swift 4 para la respuesta de 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) } }

Buscando ayuda con mi aplicación iOS. Dentro de mi aplicación, quiero abrir enlaces cliqueados desde mi dominio (EX: communionchapelefca.org) en WKWebView y luego tener enlaces de todos los demás dominios (EX: google.com) abiertos en Safari. Preferiría hacer esto también de manera progrógica ya que así es como mi código ya está configurado.

He encontrado algunas soluciones en stackoverflow ( here , here , here y here ), pero todas parecen estar basadas en Obj-C y estoy buscando una solución con Swift. gracias por adelantado.

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)


Aquí hay un código de muestra de la respuesta al swift escrito en obj c.

- (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); } }


Haga una función para decidir dónde cargar la 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) } }

Uso:

loadURLString("http://www.communionchapelefca.org/app-home") // Open in myWebView loadURLString("http://www.apple.com") // Open in Safari


Mi solución swift 3:

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) } }

No olvide también configurar el delegado

public override func loadView() { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self webView.navigationDelegate = self view = webView }


Para Swift 3.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) } } }


Puede implementar WKNavigationDelegate , agregar el método decidePolicyForNavigationAction y verificar allí el tipo de navegación y la URL solicitada. He usado google.com a continuación, pero puedes cambiarlo a tu dominio:

Xcode 8.3 • Swift 3.1 o posterior

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) } else { print("Open it locally") decisionHandler(.allow) } } else { print("not a user click") decisionHandler(.allow) } } }


Xcode 9.3, Swift 4

La fuente: https://developer.apple.com/documentation/webkit/wkwebview

import UIKit import WebKit class ViewController: UIViewController, WKUIDelegate { var webView: WKWebView! override func loadView() { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() let myURL = URL(string: "https://www.apple.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest) }}