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

Posted

技术标签:

【中文标题】无法访问 [AnyHashable:Any] 类型的值 - Swift 4【英文标题】:Unable to access values of type [AnyHashable:Any] - Swift 4 【发布时间】:2018-07-23 05:55:06 【问题描述】:

我正在尝试从 [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)
    

在打印 userInfo 时获取数据

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

【问题讨论】:

请search on the error。这已经讨论了很多很多次了。 @rmaddy 我已经在堆栈溢出时查找此错误,但它们与 [AnyHashable: Any] 类型无关 请将代码、数据、日志、错误消息等以文本(而非图像)形式发布,以便搜索 像这样添加一个守卫:guard let info = userInfo as? [String: Any] else return then 你可以检查一下,guard let aps = info["gcm.notification.data"] as? [String: Any],让 data = aps["filters"] as? String else return 我想这会起作用。 @ShivamPokhriyal 我已经发布了解决问题的答案,感谢您的帮助:) 【参考方案1】:

我解决了这个问题,因为我收到的信息是 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)")
                    
                
             

【讨论】:

【参考方案2】:

从 [AnyHashable("gcm.notification.data")] 获取数据

if let aps = userInfo["aps"] as? NSDictionary, let notificationData = userInfo["gcm.notification.data"] as? NSString 

          var dictonary:NSDictionary?
            if let data = notificationData.data(using: String.Encoding.utf8.rawValue) 
                do 
                    dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary

                    if let alertDictionary = dictonary 
                        print(alertDictionary)
                    
                 catch
                    print(error)
                

【讨论】:

以上是关于无法访问 [AnyHashable:Any] 类型的值 - Swift 4的主要内容,如果未能解决你的问题,请参考以下文章

将 userInfo [AnyHashable: Any] 转换为 [String: Any]

错误:键入 [AnyHashable: Any]?没有下标成员 (Swift)

Dictionary<AnyHashable: Any> 在 Swift 3 中 Any 可能持有 nil 值

在 SwiftUI 上的 Firebase 中使用 updateData 函数时出错

JSONSerialization.jsonObject 返回 nil

在 Swift 3 中接收远程通知