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?
How do I convert a WKScriptMessage.body to a struct?
4.2k views Asked by rawbee At
3
There are 3 answers
1
On
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)")
}
}
0
On
Your defined struct
struct EventType:Codable{
let status: Int!
let message: String!
}
WKScriptMessageHandler protocol method
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
do {
let jsonData = try JSONSerialization.data(withJSONObject: message.body)
let eventType = try JSONDecoder().decode(EventType.self, from: jsonData)
} catch {
print("fatalError")
}
}
What about safe type casting to, for example, dictionary?
Or as an option, you can send body as json string and serialise it using codable.