Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor WKWebView page load progress in Swift?

Here is my code :

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.uiDelegate = self
    webView.navigationDelegate = self

    webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)        
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "estimatedProgress") {
        progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        print(webView.estimatedProgress)
    }
}

but the estimatedProgress just showing two float number (0.1 and 1.0) and it is not working i think. i used Alamofire progress and it change in miliseconds that makes my UI better but this code is not work fine...

Is anyone can help me with progress of webView ?

like image 306
Salar Soleimani Avatar asked Dec 27 '17 07:12

Salar Soleimani


2 Answers

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
}
like image 84
m_katsifarakis Avatar answered Sep 18 '22 22:09

m_katsifarakis


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
    }
}
like image 45
Vladislav Avatar answered Sep 16 '22 22:09

Vladislav