问题
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