![](/img/trans.png)
[英]swift 3.0 How can I access `AnyHashable` types in `Any` in Swift 3?
[英]Unable to access values of type [AnyHashable:Any] - Swift 4
我試圖從類型為[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"}]
從[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)
}
我解決了這個問題,因為我收到的信息是NSString類型(String中的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)")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.