How to check if WkWebView finish loading in Objective-C?

前端 未结 3 755
星月不相逢
星月不相逢 2021-01-01 08:12

I want to load HTML pages using WkWebView and I want to show the page just after it\'s finished loading. As long as it\'s loading I would like to show an activity indicator

3条回答
  •  情歌与酒
    2021-01-01 08:58

    For anyone who is experiencing the issue of a webpage containing multiple frames and therefore doing multiple loads which interrups your load animation, I have implemented the following and it works for me in all the situations I have come across so far:

    Swift:

    var loadCount: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        startLoading()
        webview.navigationDelegate = self
        let request = URLRequest(url: url)
        webview.load(request)
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        loadCount += 1
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    
        loadCount -= 1
    
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
            if self?.loadCount == 0 {
                self?.stopLoading()
            }
        }
    
    }
    

    The basic idea is to start your load animation before you request the url, then count each request being made and only stop the load animation when your request count == 0. This is done after a slight delay as I find that some frames queue up requests synchronously so the next load will begin before the 0.1 second delay has completed.

    ( ͡° ͜ʖ ͡°)

提交回复
热议问题