WKWebView - Open external link websites in Safari

How can I open links for external websites in Safari and keep internal looks in the WKwebview? Also how can I open links with target= _blank that want to open in a new window. Right now the link is not doing anything...


//
//  ViewController.swift
//  WKWebView
//


import UIKit
import WebKit


class ViewController: UIViewController {


    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view, typically from a nib.
        let url = "https://www.example.com"
        let request = URLRequest(url: URL(string: url)!)
        self.webView.load(request)
        self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
        
        // Page Scrolling - false or true
        webView.scrollView.isScrollEnabled = false
        
    }


    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "loading" {
            
            if webView.isLoading {
                
                activityIndicator.startAnimating()
                activityIndicator.isHidden = false
                
            }else {
                
                activityIndicator.stopAnimating()
                activityIndicator.isHidden = true
                
            }
            
        }
        
    }


}

Replies

The droid you’re looking for is

WKNavigationDelegate
.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I'm not sure I understand.

The web view calls its navigation delegate whenever the user navigates around the site. Your implementation gets to allow or cancel such navigation. So, for example, if you want a specific page to load in Safari, you can:

  1. Implement the navigation delegate.

  2. Have it watch for that page.

  3. Allow any navigation that’s not to that page.

  4. Cancel any navigation to that page, so it doesn’t open in the web view.

  5. Then use open(_:options:completionHandler:) to open the page in Safari.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"