Greg Williams Greg Williams - 2 months ago 29
iOS Question

WKWebView open links from certain domain in safari

Looking for some help with my iOS app. Within my app I am wanting to open clicked links from within my domain (EX: communionchapelefca.org) in WKWebView and then have links from all other domains (EX: google.com) open in Safari. I would prefer to do this progrmatically as well since that is how my code is already setup.

I have found a few solutions on stackoverflow (here, here, here, and here) but they all seem to be Obj-C based and I am looking for a solution using Swift. thanks in advance.

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)

Answer

You can implement WKNavigationDelegate, add the decidePolicyForNavigationAction method and check there the navigationType and requested url. I have used google.com below but you can just change it to your domain:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    let wv = WKWebView(frame: UIScreen.mainScreen().bounds)
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url =  NSURL(string: "https://www.google.com") else { return }
        wv.navigationDelegate = self
        wv.loadRequest(NSURLRequest(URL: url))
        view.addSubview(wv)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .LinkActivated  {
            if let newURL = navigationAction.request.URL,
                host = newURL.host where !host.containsString("www.google.com") &&
                UIApplication.sharedApplication().canOpenURL(newURL) &&
                UIApplication.sharedApplication().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)
        }
    }
}