Determinate finish loading website in webView with

2020-01-29 08:40发布

i'm trying to create a webapp with swift in xcode, this is my current code:

IBOutlet var webView: UIWebView!

    var theBool: Bool = false
    var myTimer = NSTimer()
    @IBOutlet var progressBar: UIProgressView!

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

I've a question, How i can determinate the finish loading of the page in webView?

Do you know a documentation that contains all the definitions of the WebView? I mean .. (start / end load, the current url, title page, etc ..)?

(Sorry for my English).

2条回答
Ridiculous、
2楼-- · 2020-01-29 09:26

For WKWebview there is also wknavigationdelegate didfinish, but not do the trick as the SO question WKWebView didn't finish loading, when didFinishNavigation is called - Bug in WKWebView? and this answer show.

I also found when the page to load is very complicate and dinamic, UIWebview's webViewDidFinishLoad(- webView: UIWebView) also not works.

And I think use native swift or objective-c to detect when the page is loaded is a bad choice. The more flexable and effective way is to use javascript to call the native swift code when page finishing loading. What's more this also work for a specific dom finishing loading event and very dynamic content.

For how to call swift from javascript refer to this post.

Here is a sample code for dynamic content with anjularjs.

js,

var homeApp = angular.module('home', ['ui.bootstrap', 'ngAnimate']);
homeApp
    .directive("printerinfo",
    function() {
        return {
            restrict: "E",
            link: function() {       //call navite swift when page finishing loading
                try {
                    window.webkit.messageHandlers.testHandler.postMessage("Hello from JavaScript");
                } catch(err) {
                    console.log('The native context does not exist yet');
                }
            },

            templateUrl: "/static/tpls/cloud/app/printerinfo.php",
        }
    })

swift3,

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message.name)
    if(message.name == "testHandler") {
        //webpage content loaded
        print(Date())
        print("javascript test call swift")
    }

Here I use angularjs to check element ready, you can also refter how-to-call-a-function-after-a-div-is-ready or check-if-a-given-dom-element-is-ready or jquery-ready-equivalent-event-listener-on-elements for more.

查看更多
欢心
3楼-- · 2020-01-29 09:31

Through the UIWebView delegate call.

You need to set your webViews delegate to the current controller, and conform to the UIWebViewDelegate protocol. When the webView finished loading the page func webViewDidFinishLoad(_ webView: UIWebView) will get called.

查看更多
登录 后发表回答