swift - 无法转换 __NSCFString 类型的值

标签 swift swift3 push-notification firebase-cloud-messaging

我正在试用 FCM 消息服务。我已经设置了一切完善。当我收到来自 FCM 的消息时,出现以下错误。我不确定这里出了什么问题:

AnyHashable("google.c.a.c_id"): 1586592282379086000, AnyHashable("gcm.message_id"): 0:1515418580276498%f4373656f4373656]

Could not cast value of type '__NSCFString' (0x1b4c70040) to 'NSDictionary' (0x1b4c70b80).

2018-01-08 19:06:21.198548+0530 Ozone[1067:540436] Could not cast value of type '__NSCFString' (0x1b4c70040) to 'NSDictionary' (0x1b4c70b80).

奇怪的是我创建了一个单独的推送通知应用程序并放置了相同的代码,它在那里工作。这里可能出了什么问题?

这是一段代码:我在 let d 中收到错误:[String : Any].....line

UNNotificationPresentationOptions) -> Void) {  
           print("Handle push from foreground\(notification.request.content.userInfo)")  

            let dict = notification.request.content.userInfo["aps"] as! NSDictionary  
            let d : [String : Any] = dict["alert"] as! [String : Any]  
            let body : String = d["body"] as! String  
            let title : String = d["title"] as! String  
            print("Title:\(title) + body:\(body)")  
            self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)  

}  

有人可以帮我解决这个问题吗?我知道这是一个非常普遍的错误,但不确定为什么会出现这种情况,因为它在另一个应用程序中运行良好。

谢谢!

最佳答案

alert 键可以是字符串或字典(取决于您的服务器)。你可以试试这个。

if let dict = notification.request.content.userInfo["aps"] as? [String : Any] {

    if let d = dict["alert"] as? [String : Any],
        let body = d["body"] as? String,
        let title = d["title"] as? String {

            print("Title:\(title) + body:\(body)")
    } else if let body = dict["alert"] as? String {

        print("body:\(body)")
    }
}

而且你应该避免强制转换并且不要在 swift 中使用 NSDictionary

关于swift - 无法转换 __NSCFString 类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165070/

相关文章:

ios - 可变字符串颜色变化改变字符以显示为正方形

ios - Localytics 推送通知文本限制

android - 当应用程序在 android 中运行或不运行时,将推送通知内容显示到警报对话框中

ios - 对计算属性的 Realm 结果集合进行排序?

ios - 库 Info.plist 内的 NSLocationWhenInUseUsageDescription

ios - 来自 XIB 错误的 UITableView 和 UITableViewCell?

ios - 从字符串格式化日期 - swift3

ios - 在 Swift 3 中使用 NSNumber 和整数值

iphone - 如果您第一次选择“否”,则 PushNotification 会出现问题

swift - 字符串插值和字符串连接之间的区别