(iOS 10, Swift 3) 从 CloudKit 通知中读取 `userInfo` 字典:如何将 `[AnyHashable: Any]` 转换为 `[String : NSObject]`?
(iOS 10, Swift 3) Reading `userInfo` dictionary from a CloudKit notification: How do I cast `[AnyHashable : Any]` to `[String : NSObject]`?
背景
我正在尝试从我的应用程序委托中的 application:didReceiveRemoteNotification:userInfo:fetchCompletionHandler
加载 userInfo
字典。
然后我需要将 userInfo
从 [AnyHashable:Any]
转换为 [String:NSObject]
以便我可以在 CloudKit 的 CKNotification:fromRemoteNotificationDictionary
中使用它。
问题
当我这样做时:
let ui = userInfo as! [String : NSObject]
我收到错误:
'[AnyHashable:Any]' is not convertible to '[String:NSObject]'
是否有更好的方法将 userInfo
转换为合适的类型,还是我走错了路?
您只需要先将其转换为 NSDictionary
,然后再将其转换为 [String: NSObject]
。
这样试试:
CKNotification(fromRemoteNotificationDictionary: userInfo as NSDictionary as! [String: NSObject])
如建议的那样,删除所有强制转换并使用 userInfo 就足够了 Swift 3 正确处理事情。
NSString.localizedStringWithFormat("%@",(notification.userInfo as! [String: AnyObject] as! [String : NSObject])["theKeyValue"]!)
这就是我得到字符串的方式。欢迎指正。
背景
我正在尝试从我的应用程序委托中的 application:didReceiveRemoteNotification:userInfo:fetchCompletionHandler
加载 userInfo
字典。
然后我需要将 userInfo
从 [AnyHashable:Any]
转换为 [String:NSObject]
以便我可以在 CloudKit 的 CKNotification:fromRemoteNotificationDictionary
中使用它。
问题
当我这样做时:
let ui = userInfo as! [String : NSObject]
我收到错误:
'[AnyHashable:Any]' is not convertible to '[String:NSObject]'
是否有更好的方法将 userInfo
转换为合适的类型,还是我走错了路?
您只需要先将其转换为 NSDictionary
,然后再将其转换为 [String: NSObject]
。
这样试试:
CKNotification(fromRemoteNotificationDictionary: userInfo as NSDictionary as! [String: NSObject])
如建议的那样,删除所有强制转换并使用 userInfo 就足够了 Swift 3 正确处理事情。
NSString.localizedStringWithFormat("%@",(notification.userInfo as! [String: AnyObject] as! [String : NSObject])["theKeyValue"]!)
这就是我得到字符串的方式。欢迎指正。