How to monitor WKWebView page load progress in Swift?
This should work properly on Swift 5:
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!
private var observation: NSKeyValueObservation? = nil
override func viewDidLoad() {
super.viewDidLoad()
// load website or HTML page
webView.load(NSURLRequest(url: URL(string: "https://www.apple.com")!) as URLRequest)
// add observer to update estimated progress value
observation = webView.observe(\.estimatedProgress, options: [.new]) { _, _ in
self.progressView.progress = Float(self.webView.estimatedProgress)
}
}
deinit {
observation = nil
}
Swift 4.0
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// load website or HTML page
self.webView.load(NSURLRequest(url: URL(string: "https://www.apple.com")!) as URLRequest);
//add observer to get estimated progress value
self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);
}
// Observe value
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
print(self.webView.estimatedProgress);
self.progressView.progress = Float(self.webView.estimatedProgress);
}
}
New Swift KVO approach
class ViewController: UIViewController {
private lazy var webView = WKWebView()
private var observation: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
observation = webView.observe(\WKWebView.estimatedProgress, options: .new) { _, change in
print("Loaded: \(change)")
}
}
deinit {
self.observation = nil
}
}