简体   繁体   中英

UIWebview/WKWebView javascript call handle two return values?

I have one javascript function which return multiple values. I am trying to call that function in my iOS app using Webview. 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.

//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

//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.

Javascript code:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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