Search code examples
swiftwknavigationdelegate

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


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?


Solution

  • 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)