我想将JSON数据传递给与Web视图相关的javascript函数。但是我无法从Javascript函数中获取响应数据

时间:2018-01-30 16:14:43

标签: javascript ios json swift webview

打印' b'价值,我变得空虚。意味着我发送的数据是错误的。

我做错了吗?

这是我的代码

Swift 4.0

let colorArray = [["Red", "Blue", "Green"], ["Red"], ["Blue", "Green"], ["Green"], ["Blue"], ["Blue", "Green", "Red"]]

let flattened = colorArray.reduce([], +)
let set = NSCountedSet(array: flattened)
for element in set {
    print("\(element) = \(set.count(for: element))")
}

这是我的Javascript功能

let inputPayload: Dictionary = ["wellname": ["answer": "firstName"]]

if JSONSerialization.isValidJSONObject(inputPayload) {
  do {
    let rawData =
      try JSONSerialization.data(withJSONObject: inputPayload, options: [])

    let b = webView.stringByEvaluatingJavaScript(from: "downloadComplete(\(rawData))") !
      print(b)
  } catch {

  }
}

1 个答案:

答案 0 :(得分:2)

<强>目标c

- (void)runJavaScriptCallback:(NSString *) jsonString {
    NSString *exec_template = @"downloadComplete(\'%@\');";
    NSString *exec = [NSString stringWithFormat:exec_template, jsonString];

    [webView evaluateJavaScript:exec completionHandler:nil];
}

Swift 4

func runJavaScriptCallback(jsonString: String) {
    webView.evaluateJavaScript("downloadComplete(\(jsonString))") { result, error in
        guard error == nil else {
            print(error)
            return
        }
    }
}

<强>的Javascript

var downloadComplete = (bridgeMsg) => {
  // escape newline character from iOS sdp
  bridgeMsg = bridgeMsg.replace(/\r?\n|\r/g, '\\r\\n');

  const msg = JSON.parse(bridgeMsg);
  // do whatever you want with the parsed json object
};