bridge在registerHandler
时可以获取data
,如果前端传过来的data
是个json数据,我们却无法直接将data作为json处理。
这是由于JavaScriptBridge
对前端传来的data做了处理,data是个对象,而不是json。所以我们需要将data对象转成json再进行处理:
1 2 3 4 5 6 7 8
| func bridgeJson(from data:Any) ->Any? { let jsonStr = "\(data)" if let jsonData = jsonStr.data(using: .utf8, allowLossyConversion: false), let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers){ return json } return nil }
|
响应桥接事件示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| bridge?.registerHandler("goHref", handler: { [unowned self] (data, callback) in if let obj = data, let json = self.bridgeJson(from: obj), let model = WebHrefModel.decode(json as? [String:Any]) { if let href = model.href { self.urlRecords.append(href) self.loadUrl(href) } if let title = model.name { self.navigationItem.title = title self.titleRecords.append(title)
} if let callback = callback { callback("success") } }
})
|