【发布时间】:2019-01-06 12:48:38
【问题描述】:
我在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"]是一个String,一个JSON Stringified。所以应该是if let jsonStringified = dict["message"] as? String。我不使用Mapper,而是使用标准工具:伪代码中的let jsonData = jsonStringified.data(encoding: .utf8); let jsonDict = try? JSONSerialization.jsonObject(data: jsonData)。 -
@Larme I',去试试你的代码
-
@Larme 请发表您的评论作为答案。这是正确的。感谢您纠正我
-
Mapper<NotificationModel>().map(JSON: response):Mapper有办法处理(NS)Data或(NS)StringJSON 吗?因为那应该避免转型。我希望对于更高级别的第三个库它确实如此。是这样吗?喜欢Mapper<NotificationModel>().map(JSONString: jsonStringified)或Mapper<NotificationModel>().map(JSONData: jsonData)你在用这个吗:github.com/lyft/mapper/blob/master/Sources/Mapper.swift? -
@Larme 是的。我只是将 jsonDict 转换为 [String: Any] 并将其交给 Mapper,它成功地给了我一个模型
标签: swift push-notification apple-push-notifications