简体   繁体   English

无法从 WKUserContentController didReceive WKScriptMessage 获取字符串数据

[英]Can't get string data from WKUserContentController didReceive WKScriptMessage

My method is called:我的方法称为:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("message.body: \(message.body)")
    
    if let messageBody = message.body as? [String: Any] {
        print("messageBody: \(messageBody)") //this is not triggered
        if let data = messageBody["data"] as? NSString {
            print("DATA: \(data)")
        }
    }

The message body is:消息正文是:

message.body: {"type":3,"data":"{\"title\":\"Verzamelen\",\"content\":\"Loongegevens...\"}"}

But after that I'm not able to retrieve the "data" field.但在那之后我无法检索“数据”字段。 What am I missing?我错过了什么?

The issue was probably related to the backslash escapes in the String.该问题可能与字符串中的反斜杠转义有关。 What worked is decoding it with JSON decoder:有效的是使用 JSON 解码器对其进行解码:

struct ScriptMessage: Codable {
    let type: Int
    let data: String
}


func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    
    guard let bodyString = message.body as? String,
          let bodyData = bodyString.data(using: .utf8) else {
        return
    }
    
    if let bodyStruct = try? JSONDecoder().decode(ScriptMessage.self, from: bodyData) {
        print(bodyStruct.data)
    }
}

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

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