在WKWebView完成加载和抓取特定页面后执行某些操作

时间:2017-08-22 07:07:49

标签: swift url webview uibutton reachability

我尝试做的只是在WKWebView我使用完成加载和抓取页面后才执行操作。

这里是webView的代码:

    let webView = WKWebView()

    let url = URL(string: "https://web.spaggiari.eu/home/app/default/menu_webinfoschool_genitori.php?custcode=")!
        let request = URLRequest(url: url)
        webView.load(request)

我想要做的是将按钮显示为" Connect"只有在进程捕获后(该特定进程,而不是每次webView完成加载时)。现在我使用DispatchQueue等待几秒钟,希望页面及时加载。

 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4)) { 
            UIView.animate(withDuration: 0.8, animations: {
                self.registerButton.alpha = 1
                self.registerButton.isEnabled = true
            })
            UIView.animate(withDuration: 0.8, delay: 0.4, animations: {
                self.blurButton.alpha = 1
            })
        }

我正在使用Xcode和Swift3

2 个答案:

答案 0 :(得分:0)

此代码表示该页面已满载,这可能对您有所帮助

func webpageFullyLoaded(_ str: String) {


    if (str == "complete") || (str == "interactive") {

        print("page completely loaded")

    }
}

func webViewDidFinishLoad(_ webView: UIWebView) {


    webpageFullyLoaded(webView.stringByEvaluatingJavaScript(from: "document.readyState"))
}

答案 1 :(得分:0)

WKWebView有此代表

/*! @abstract The web view's navigation delegate. */
    weak open var navigationDelegate: WKNavigationDelegate?

WKNavigationDelegate : 符合WKNavigationDelegate协议的类可以提供  跟踪主框架导航进度和决定的方法  主帧和子帧导航策略

这个委托有一个方法,可以帮助你

/*! @abstract Invoked when a main frame navigation completes.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     */
    @available(iOS 8.0, *)
    optional public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

所以你可以试试这个

    func loadPage() {
        let webView = WKWebView()
        webView.navigationDelegate = self
        let url = URL(string: "https://web.spaggiari.eu/home/app/default/menu_webinfoschool_genitori.php?custcode=")!
        let request = URLRequest(url: url)
        webView.load(request)

    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Do your work here
    }

另外,请确保此处的self符合WKNavigationDelegate

<强>更新

要在同一个WKWebView中处理不同网页的加载,

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
        print("Page Being loaded is \(navigationAction.request), you can do your work here")
        decisionHandler(.allow)
    }

您可以在导航委托here

中详细了解可以执行的操作