Webview - Open IOS App with Google Chrome

Asked

Viewed 298 times

1

Hello, developing an app for IOS, but would like it to open with Google Chrome instead of Safari browser.

Could one 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 answer

1


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)
}
  • Thanks for the answer George, I’ll test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.