WebView-open IOS app with Google Chrome
Hello, developing an app for IOS, but I would like it to open with Google Chrome instead of the Safari browser.
Could any of you help me?
Code:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.naivgationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://site.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let requestURL = navigationAction.request.url else {
decisionHandler(.allow)
return
}
//Aqui você tem a URL, e pode fazer o que quiser com ela.
decisionHandler(.allow)
}
}
1
Author: George Gomes, 2019-09-17
1 answers
Replace the last function with this one, it will check if it is possible to open with chrome and send the link
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let requestURL = navigationAction.request.url else {
decisionHandler(.allow)
return
}
if(navigationAction.navigationType == WKNavigationType.linkActivated) {
// Remove http:// ou https:// e substitui com googlechrome://
let newLinkWithHttp = requestURL.absoluteString.replacingOccurrences(of: "http://", with: "googlechrome://")
let newLinkWithHttps = newLinkWithHttp.replacingOccurrences(of: "https://", with: "googlechrome://")
// Verifica se é possível abrir com o chrome, caso não seja abre o link normal com o safari
if UIApplication.shared.canOpenURL(URL(string: newLinkWithHttps)!) {
UIApplication.shared.open(URL(string: newLinkWithHttps)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.open(requestURL, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
1
Author: George Gomes, 2019-09-18 17:38:30