How do I get WKWebView.evaluateJavaScript to return data in a function call

拜拜、爱过 提交于 2021-02-07 19:51:02

问题


I'm working on some WKWebView parsing routines. I'm trying to validate that I've navigated to a page properly by checking it's document.title. I wrote a function to do this work, but I can't seem to figure out how to return the HTML data from the function or do the evaluation in the function and return a BOOL. I know I'm doing an async call here, but not sure how to wait for that call to end and feed the response back from my function call.

Here is my function:

func checkTitle (forWebView webView: WKWebView, title: String) -> String{


webView.evaluateJavaScript("document.title", completionHandler: { (innerHTML, error ) in
    let titleString = innerHTML as? String

    return (titleString)

})

This throws a compiler error. I've tried to declare the variable outside the call and then assign and return it after, but it tries to execute that before the async call is complete.


回答1:


you should use a completion handler, something like this:

func checkTitle (forWebView webView: WKWebView, title: String, completion: @escaping (_ titleString: String?) -> Void) {

   webView.evaluateJavaScript("document.title", completionHandler: { (innerHTML, error ) in

        // Logic here
        completion(innerHTML as? String)  
    })
}


来源:https://stackoverflow.com/questions/48615536/how-do-i-get-wkwebview-evaluatejavascript-to-return-data-in-a-function-call

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