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"}]
Get the data from [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)
}
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)")
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.