Mirko Brombin Mirko Brombin - 3 months ago 165
iOS Question

Progressbar WebView in Swift

I'm writing a webapp in swift with xcode.
I've a question "How can I add a progressbar that shows me the loading of each page?"

@IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}


(Sorry for my english)

Answer

You can find a very good answer in this post. You can just add a progress bar as a subview to your webview. The main problem is the accuracy of the progress bar. The proposed answer is to begin by animating it constantly, block it at 95% when still loading and when your request is complete, zip it all the way to 100%.

Here's a solution in Swift:

Add these properties:

//Add this progress view via Interface Builder (IBOutlet) or programatically
let myProgressView: UIProgressView

var theBool: Bool
var myTimer: NSTimer

These functions will fill the progress view. You can play with the parameters:

func funcToCallWhenStartLoadingYourWebview() {
    self.myProgressView.progress = 0.0
    self.theBool = false
    self.myTimer = NSTimer.scheduledTimerWithTimeInterval(0.01667, target: self, selector: "timerCallback", userInfo: nil, repeats: true)
}

func funcToCallCalledWhenUIWebViewFinishesLoading() {
    self.theBool = true
}

func timerCallback() {
    if self.theBool {
        if self.myProgressView.progress >= 1 {
            self.myProgressView.hidden = true
            self.myTimer.invalidate()
        } else {
            self.myProgressView.progress += 0.1
        }
    } else {
        self.myProgressView.progress += 0.05
        if self.myProgressView.progress >= 0.95 {
            self.myProgressView.progress = 0.95
        }
    }
}
Comments