Determinate finish loading website in webView with Swift in Xcode

前端 未结 2 1806
有刺的猬
有刺的猬 2020-12-03 14:59

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          


        
相关标签:
2条回答
  • 2020-12-03 15:27

    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.

    0 讨论(0)
  • 2020-12-03 15:33

    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.

    0 讨论(0)
提交回复
热议问题