从EvaluateJavaScript函数的完成处理程序返回HTML字符串 [英] Return HTML string from the completion handler of the evaluateJavaScript function

查看:99
本文介绍了从EvaluateJavaScript函数的完成处理程序返回HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不是第一个问这个问题的人,但我无法解决问题.我正在尝试使用Swift 3的Xcode中的 evaluateJavaScript 从HTML中提取一段字符串,并且该文本在完成处理程序中称为 value ,所以我喜欢这个:

  var userName = String()func takeData(){webView.evaluateJavaScript("document.querySelectorAll('.name')[0] .innerHTML"){(值,错误)在如果让valueName = value as?细绳 {self.userName = valueName}打印(值)打印(错误)}}print(名称为:\(self.userName)") 

问题在于控制台仅打印:名称为()

解决方案

问题是您在异步函数完成执行之前就打印了该值.您有几种解决方案来解决此问题.您可以实现 takeData 来将completionHandler作为其输入参数之一,可以使用 GCD 来使语句以预期的顺序执行,也可以使用第三方库,例如 PromiseKit 为您处理异步请求,因此它们的行为类似于具有返回值的普通函数./p>

我将为您提供一个有关完成处理程序的示例:

  func takeData(completionHandler:@escaping(_ userName:String?)->无效){webView.evaluateJavaScript("document.querySelectorAll('.name')[0] .innerHTML"){(值,错误)在如果让valueName = value as?细绳 {completeHandler(valueName)}打印(值)打印(错误)completeHandler(无)}} 

您可以像这样使用来自completionHandler的值:

  takeData(completionHandler:{打印(用户名)}) 

I know that I'm not the first one to ask this but I can't solve the problem. I'm trying to take a piece of string from HTML using evaluateJavaScript in Xcode with Swift 3 and the piece of text is called value inside the completion handler, so I did like this:

var userName = String()

   func takeData() {
        webView.evaluateJavaScript("document.querySelectorAll('.name')[0].innerHTML") { (value, error) in

            if let valueName = value as? String {
                self.userName = valueName
            }
            print(value)
            print(error)
        }

    }

print(" The name is : \(self.userName)") 

The problem is that the console just prints: The name is ()

解决方案

The problem is that you are printing the value before your asynchronous function could finish execution. You have several solutions to solve this issue. You can either implement takeData to have a completionHandler as one of its input parameters, use GCD to make your statements execute in the expected order or use a 3rd party library, such as PromiseKit to handle the async requests for you, so they will behave like normal functions with a return value.

I will give you an example with the completion handler:

func takeData(completionHandler: @escaping (_ userName: String?) -> Void){
    webView.evaluateJavaScript("document.querySelectorAll('.name')[0].innerHTML") { (value, error) in
        if let valueName = value as? String {
            completionHandler(valueName)
        }
        print(value)
        print(error)
        completionHandler(nil)
    }
}

You use the value from the completionHandler like this:

takeData(completionHandler: { userName in
    print(userName)
})

这篇关于从EvaluateJavaScript函数的完成处理程序返回HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆