我在didreceiveRemoteNotification
中收到了通知,但是我无法将userInfo转换为类型为[String: Any]的字典
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let dict = userInfo as! [String: Any]
if let response = dict["message"] as? [String: Any], let baseResponse = Mapper<NotificationModel>().map(JSON: response) {
//do some stuff
}
}
当我尝试将dict["message"]强制转换为 [String: Any] 时,出现错误并提示:
无法将类型 '__NSCFString' (0x1cfa84f90) 强制转换为 'NSDictionary' (0x1cfa85bc0)。
这是在控制台中打印 dict["message"] 时的输出结果:
▿ Optional<Any>
- some : {"sender":
{"avatar_url":"http:\/\/api.moneyar.com\/APIs\/images\/15783070400.jpg","user_id":"15783","name":"mahdi moqadasi"}
,"conversation_id":"15783"
,"message_id":103597,
"time":1546778745,
"type":1,"message":"foo"
}
dict["message"]
是一个字符串,一个 JSON 字符串。所以应该使用if let jsonStringified = dict["message"] as? String
。我不使用Mapper
,而是使用标准工具:伪代码中的let jsonData = jsonStringified.data(encoding: .utf8); let jsonDict = try? JSONSerialization.jsonObject(data: jsonData)
。 - LarmeMapper<NotificationModel>().map(JSON: response)
:Mapper
是否有处理(NS)Data
或(NS)String
JSON的方法?因为这样可以避免转换。我希望对于一个更高级别的第三方库来说是这样的。是这种情况吗?例如Mapper<NotificationModel>().map(JSONString: jsonStringified)
或Mapper<NotificationModel>().map(JSONData: jsonData)
,你使用的是这个吗:https://github.com/lyft/mapper/blob/master/Sources/Mapper.swift? - Larme