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

﹥>﹥吖頭↗ 提交于 2019-12-03 22:05:44

I think the WKNavigationDelegate's webView:didFinishNavigation: delegate callback is what you're looking for.

Configure and present your activity indicator when you start to load and then stop and remove it from view when the callback is called.

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 4.2:

var loadCount = 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) {
        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.

( ͡° ͜ʖ ͡°)

for swift 4.2:

func webView(_ webView: WKWebView,
                 didFinish navigation: WKNavigation!){
        print("loaded")
}

be sure to set delegate for webView in didLoad (or similar)

webView.navigationDelegate = self
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!