How do I convert a WKScriptMessage.body to a struct?

Viewed 2146

I set up the WKScriptMessageHandler function userContentController(WKUserContentController, didReceive: WKScriptMessage) to handle JavaScript messages sent to the native app. I know ahead of time that the message body will always come back with the same fields. How do I convert the WKScriptMessage.body, which is declared as Any to a struct?

2 Answers

What about safe type casting to, for example, dictionary?

let body = WKScriptMessage.body
guard let dictionary = body as? [String: String] else { return }

Or as an option, you can send body as json string and serialise it using codable.

struct SomeStruct: Codable {
    let id: String
}

guard let bodyString = WKScriptMessage.body as? String,
      let bodyData = bodyString.data(using: .utf8) else { fatalError() }

let bodyStruct = try? JSONDecoder().decode(SomeStruct.self, from: bodyData)

In SwiftUI message.body is String object. You can convert the body in dictionary like this:

            if let bodyString = message.body as? String {
            let data = Data(bodyString.utf8)
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    guard let body = json["body"] as? [String: Any] else {
                        return
                    }
                    //use body object
                }
            } catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }
        }
Related