[英]stringByEvaluatingJavaScript(from:) return value equivalent
I know that this question seems to have been asked but I have a different problem with this method.我知道似乎有人问过这个问题,但我对这种方法有不同的问题。
UIWebView's
- stringByEvaluatingJavaScript(from:)
is synchronously returning a String?
UIWebView's
- stringByEvaluatingJavaScript(from:)
同步返回一个String?
value.价值。
The WKWebView
equivalent evaluateJavaScript(_:completionHandler:)
works with a complitionHandler. WKWebView
等效的evaluateJavaScript(_:completionHandler:)
与WKWebView
一起使用。
I'm working with legacy code and I have stringByEvaluatingJavaScript(from:)
affecting thousands of lines in the code and can be found everywhere and in a lot of functions that return values (not using blocks).我正在处理遗留代码,我有
stringByEvaluatingJavaScript(from:)
影响代码中的数千行,并且可以在任何地方和许多返回值的函数中找到(不使用块)。
very simple example -非常简单的例子——
@discardableResult func js(_ script: String) -> String? {
let callback = self.stringByEvaluatingJavaScript(from: script)
if callback!.isEmpty { return nil }
return callback
}
now that I'm changing to evaluateJavaScript(_:completionHandler:)
I will need the js(script:)
method to be handled with a block, and methods that use that method needs to change and so on...现在我要更改为
evaluateJavaScript(_:completionHandler:)
我将需要使用块处理js(script:)
方法,并且使用该方法的方法需要更改等等......
I think that in order to fix this without changing all my code I need evaluateJavaScript(_:completionHandler:)
to synchronously return String?
我认为为了在不更改我所有代码的情况下解决这个问题,我需要
evaluateJavaScript(_:completionHandler:)
来同步返回String?
. .
Does anybody know how this can be achieved?有谁知道这是如何实现的? or maybe have a different solution?
或者可能有不同的解决方案?
Found it -找到了 -
Add this to your WKWebview
extension to wrap evaluateJavaScript(_:completionHandler:)
in a synchronous warp like in UIWebview
-将此添加到您的
WKWebview
扩展中,以在UIWebview
这样的同步扭曲中包装evaluateJavaScript(_:completionHandler:)
WKWebview
evaluateJavaScript(_:completionHandler:)
-
open func stringByEvaluatingJavaScript(from script: String) -> String?
{
var finished = false
var stringResult: String? = nil
evaluateJavaScript(script) { (result, error) in
if error == nil, let result = result
{
stringResult = String(describing: result)
}
finished = true
}
while !finished
{
RunLoop.current.run(mode: .default, before: Date.distantFuture)
}
return stringResult
}
I'm not sure what types can be returned in the result
so watch out for that.我不确定
result
可以返回哪些类型,因此请注意这一点。 other then that works great.否则效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.