Search code examples
iosswifttimerswift3uiprogressview

UIProgressView loading bar with percentage


I want to make a loading bar in Swift 3 for my iOS project. I'm doing a web view for the moment and need to do this loading bar to show in between the actions. I know it is fake loading bar and I saw code in Objective-C and tried to make something out of it in Swift but I'm afraid that my logic is wrong, since I'm new in Swift.

The problem I'm having is that I don't acctually know if I set vars theBool and timer to the right place and I dont know how to use Timer().

And to tell you what I see when I run the app, Progress bar is showing the whole time, but it's not loading.

This is my code so far

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var progressView: UIProgressView!

    var theBool = false
    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        progressView.progress = 0.0

        //Reading the webview
        let websiteURL = URL(string: "http://google.com")
        let websiteURLRequest = URLRequest(url: websiteURL!)
        webView.loadRequest(websiteURLRequest)
    }

    func webViewDidFinishLoad (){
        if webView.isLoading == true {
        theBool = true
        }
    }

    func handleProgress () {
        if (theBool){
            if (progressView.progress >= 1) {
                progressView.isHidden = true
                timer.invalidate()
            } else {
                progressView.progress += 0.1
            }
        } else {
            progressView.progress += 0.05
            if (progressView.progress >= 0.95) {
                progressView.progress = 0.95
            }
        }
    }

    /*
    func addValsToProgress () ->String {
        if (webViewLoading() == true) {
            view.progressView.setProgre
        }
    }
    */
}

Solution

  • So after a few tries with the solutions you posted, I found an answer. It's so simple that I was ashamed.

    It works like a charm. Thank you all for your answers :)

    @IBOutlet var webView: UIWebView!
    @IBOutlet var progressView: UIProgressView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://google.com")
        let request = NSURLRequest(url: url as! URL)
        webView.loadRequest(request as URLRequest)
        webView.delegate=self
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
    
        self.progressView.setProgress(0.1, animated: false)
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
    
        self.progressView.setProgress(1.0, animated: true)
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    
        self.progressView.setProgress(1.0, animated: true)
    }