如何检测UIWebView何时完全加载Swift

时间:2016-07-15 07:31:45

标签: objective-c iphone swift cocoa-touch

当webview完全加载时,我需要以编程方式重置webview框架。添加了delegate方法,但是对于单个请求,多次调用webViewDidFinishLoad。如何在webViewDidFinishLoad中检查加载是否完成?

2 个答案:

答案 0 :(得分:3)

您可以使用UIWebViewDelegate

有两种方法可以在完成时检测,一种方法成功,另一种方法有错误

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
    }
}

不要忘记在delegateself(根据@Jim推荐)设置为viewDidLoaddidSet

myWebView.delegate = self

答案 1 :(得分:0)

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")
    }
}