简体   繁体   English

UIWebview / WKWebView javascript调用处理两个返回值?

[英]UIWebview/WKWebView javascript call handle two return values?

I have one javascript function which return multiple values. 我有一个JavaScript函数,可以返回多个值。 I am trying to call that function in my iOS app using Webview. 我正在尝试使用Webview在我的iOS应用中调用该函数。 I have tried searching for similar question but found nothing. 我曾尝试搜索类似的问题,但一无所获。 Check the code below. 检查下面的代码。 FYI single return value works fine and I am calling this javascript after "webview did finish" delegate called. 仅供参考,单返回值可以正常工作,我在调用“ webview完成”委托后调用此javascript。

//Javascript function
function listABCs() constant returns (uint noOfABCs, address[] retABCAddresses) {
    return (abcAddresses.length, abcAddresses);
}

//iOS code
let script = "getAbcList()"
wkWebView?.evaluateJavaScript(script, completionHandler: { (response: Any?, error:Error?) in
       print("\n Error \(String(describing: error))")
       let res = response as? String
       print("Response = \(String(describing: response))")
})

Thanks in advance. 提前致谢。

You can add a boolean once you received your value the first time set that to true 您可以在第一次将值设置为true时添加布尔值

//Create a variable received response
var receivedResponse = false

let script = "getKycList()"
wkWebView?.evaluateJavaScript(script, completionHandler: { (response: Any?, error:Error?) in
   print("\n Error \(String(describing: error))")
   if !receivedResponse {
      if let res = response as? String {
          // use the response now
          print("Response = \(res)")

         // set the receivedResponse to true
         receivedResponse = true
      }

   }

})

I solved this by returning a dictionary instead of a string and then using the dictionary in iOS to retrieve the values. 我通过返回字典而不是字符串来解决此问题,然后在iOS中使用字典来检索值。

Javascript code: JavaScript代码:

function customDictFrom(val1, val2) {

    var data_to_pass = {
        'val1': val1,
        'val2': val2
    };

    return data_to_pass;
}

function listABCs() constant returns (uint noOfABCs, address[] retABCAddresses) {
    var data_to_pass = customDictFrom(abcAddresses.length, abcAddresses);
    return data_to_pass;
}

Swift (Native) Handling: Swift(本机)处理:

let script = "getAbcList()"
wkWebView?.evaluateJavaScript(script, completionHandler: { (response: Any?, error:Error?) in
       print("\n Error \(String(describing: error))")
       let res = response as? [String: Any] //Your response is here as a dictionary
       print("Response = \(String(describing: response))")
})

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM