gpt4 book ai didi

swift - 转换 userInfo [AnyHashable : Any] to [String: Any]

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:24 25 4
gpt4 key购买 nike

我在 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"

}

最佳答案

对于以下答案,代码未针对编译器进行测试,可能存在一些可以轻松修复的拼写错误,其中一些是故意完成的以体现其背后的逻辑,而不是添加 if let/guard letas? 等是必需的,但会在解释中增加噪音。

不再重复@vadian answer ,这是正确的,并解释了失败的原因。

所以我们很清楚 dict["message"] 是一个 String

您在 JSON 首字母缩略词中似乎缺少的一条信息是代表“N”的内容:表示法。

当您打印 dict["message"] 时,您并没有真正的键/值对象,您有一个表示键值对象的字符串,但不是 Swift 表示形式。您打印了 JSON Stringified(因为它显然比十六进制数据 JSON 更具可读性)。如果在回答后打印 jsonDict,您会发现输出结构可能不同。

因此,一如既往,您的基本工具是:

Data <== data(encoding:)/init(data:encoding:) ==> String
Data <== jsonObject(with:options:)/data(withJSONObject:options:) ==> Array or Dictionary //I bypass voluntarily the specific case of String at top level

那我们开始吧!

let jsonStringifiedString = dict["message"] as String
let jsonStringifiedData = jsonStringifiedString.data(using: .utf8) as Data
let jsonDict = try JSONSerialization.jsonObject(with: jsonStringifiedData, options: []) as [String: Any]
let baseResponse = Mapper<NotificationModel>().map(JSON: jsonDict)

如果我是你,我会研究 Mapper,如果没有办法做类似的事情:

let baseResponse = Mapper<NotificationModel>().map(JSONData: jsonStringifiedData)

let baseResponse = Mapper<NotificationModel>().map(JSONString: jsonStringifiedString)

因为有时在 JSON 中嵌入了 JSONStringified,您可能需要在 StringData 上直接调用它。或者只是因为基本的 URLSession 请求在其闭包中返回了一个 Data 对象,而您想直接使用它。

关于swift - 转换 userInfo [AnyHashable : Any] to [String: Any],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54061639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com