I am trying to access a particular value from a variable that is of type [AnyHashable: Any] however, I am getting an error while accessing any value. I have browsed the internet regarding this issue, but I did not get any specific solution for it. So is there any other way to access them? Please help and thanks in advance.
Function where I am getting an error
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)
}
Fetched data on printing the userInfo
[AnyHashable("gcm.notification.data"): {"filters":"fjjnbbx zjbxzj","history":"dsfdxf","message":"value1","source":"message source"}]
I resolved the issue as the information I was receiving was of type NSString (JSON in String) not NSDictionary / [String : Any]. I have provided the working code that solved my problem below -
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)")
}
}
}