priya.vr
priya.vr

Reputation: 239

How to detect when a UIWebView has completely finished loading in Swift

I need to reset the webview frame programmatically ,when webview has completely finished loading .Delegate methods are added,but webViewDidFinishLoad is called multiple times for a single request.How can i check whether loading is complete or not in webViewDidFinishLoad?

Upvotes: 0

Views: 4335

Answers (2)

Jignesh B
Jignesh B

Reputation: 508

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet var webView : UIWebView

    var url = NSURL(string: "http://google.com")

    override func viewDidLoad() {
        super.viewDidLoad()

        //load initial URL
        var req = NSURLRequest(URL : url)
        webView.loadRequest(req)
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    }


    func webViewDidFinishLoad(webView : UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        println("BB")
    }
}

Upvotes: 0

xmhafiz
xmhafiz

Reputation: 3538

You can use UIWebViewDelegate

There are two methods to detect on finish, one with success and another with error

extension YourViewController: UIWebViewDelegate {

    func webViewDidFinishLoad(webView: UIWebView) {
        if webView.loading {
            // still loading
            return
        }

        print("finished")
        // finish and do something here
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("didFailLoadWithError \(error?.localizedDescription)")
        // error happens
    }
}

dont forget to set to your delegate to self in viewDidLoad or in didSet (as recommended by @Jim)

myWebView.delegate = self

Upvotes: 3

Related Questions