gpt4 book ai didi

ios - 无法访问 [AnyHashable :Any] - Swift 4 类型的值

转载 作者:行者123 更新时间:2023-11-28 11:53:43 26 4
gpt4 key购买 nike

我正在尝试从类型为 [AnyHashable: Any] 的变量访问特定值,但是,我在访问任何值时遇到错误。我已经浏览了有关此问题的互联网,但没有找到任何具体的解决方案。那么有没有其他方法可以访问它们?请帮助并提前致谢。

我遇到错误的函数

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
//Print full message
print(userInfo)

guard let aps = userInfo[AnyHashable("gcm.notification.data")],
let data = aps["filters"] as! String else { // Getting the error here
return
}
print(aps)
completionHandler(UIBackgroundFetchResult.newData)
}

获取打印用户信息的数据

[AnyHashable("gcm.notification.data"): {"filters":"fjjnbbx zjbxzj","history":"dsfdxf","message":"value1","source":"message source"}]

最佳答案

我解决了这个问题,因为我收到的信息是 NSString(字符串中的 JSON)类型,而不是 NSDictionary/[String : Any]。我在下面提供了解决我的问题的工作代码 -

if let notificationData = userInfo["gcm.notification.data"] as? NSString {
var dictionary : NSDictionary?
if let data = notificationData.data(using: String.Encoding.utf8.rawValue) {
do {
dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
print("DICTIONARY : \(dictionary)")
if let dict = dictionary {
print(dict["alert_message"] as? String)
// ..... and so on
}
} catch let error as NSError {
print("Error: \(error)")
}
}
}

关于ios - 无法访问 [AnyHashable :Any] - Swift 4 类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472321/

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