Search code examples
iosswiftprogress-barwkwebviewuiprogressview

Turning EstimatedProgress/ProgressView into progress bar in WKWebView


I'm having trouble figuring out how to get ProgressView, which I've converted into estimated progress into a UI progress bar that can be seen. In my output I can clearly see that it is tracking the data but nothing is shown on the UI when a test is run. I want to add a progress bar to the bottom of my navigation bar.

class CycleViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

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

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.applicationNameForUserAgent = "Version/8.0.2 Safari/600.2.5"
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView

    progressView = UIProgressView(progressViewStyle: .default)
    progressView.sizeToFit()
    progressView.progressTintColor = UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0)

}

override func viewDidLoad() {
    super.viewDidLoad()

    webView.backgroundColor = UIColor.clear
    webView.backgroundColor = UIColor(red: 0.0196, green: 0.4, blue: 0.2902, alpha: 1.0)
    webView.isOpaque = false

    self.webView.load(NSURLRequest(url: URL(string: "https://jwelsh19.wixsite.com/countryday")!) as URLRequest);

    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" {
        print(self.webView.estimatedProgress);
        self.progressView.progress = Float(self.webView.estimatedProgress);        }
}

}

Solution

  • viewDidLoad( ) is called when the view has finished loading, while loadView( ) is called when the view starts loading. Move this code in ViewDidLoad

    //progressView = UIProgressView(progressViewStyle: .default) // remove this line
    progressView.sizeToFit()
    progressView.progressTintColor = UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0)
    

    Also no need to recreate webview. just delete webview from storyboard and create it programmatically and setup his constraint with container view. add container view in storyboard which start from progressbar till bottom of viewcontroller. add your webview in container view. i checked your code and update with fix. Download code