Search code examples
iosswiftuiprogressview

No calls occurring for observeValueForKeyPath for UIProgressView in Swift


With the help of this tutorial I was adding a progress bar to my view with Swift but the observer does not get any calls of itself.

//  ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView?

    @IBOutlet dynamic var progressView: UIProgressView!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupBrowser()

        self.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)

        let website = "https://google.com"
        let site = NSURL(string: website)

        loadURLRequest(NSURLRequest(URL: site!))
    }

    func setupBrowser() {
        let wkWebView = WKWebView(frame: view.bounds)
        wkWebView.navigationDelegate = self
        webView = wkWebView

        let wkProgressView = UIProgressView(frame: view.bounds)
        progressView = wkProgressView

        self.view.insertSubview(wkWebView, belowSubview: wkProgressView)
    }

    func loadURLRequest(request: NSURLRequest) {
        webView?.loadRequest(request)
    }

    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        print("Finished navigating")
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print(1)
        if (keyPath == "estimatedProgress") {
            // TODO
        }
    }

}

Taking a look on SWIFT - KVO in xcode 6 beta 6.. observeValueForKeyPath no longer called or observeValueForKeyPath not being called didn't help. Is UIProgressView not observable? The console shows after every page load Finished navigating but not once 1.


Solution

  • It should be

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

    You observe the webview estimateProgress,get the progress,then set the progress of the progressView