ios - 无法将“__NSCFString”类型的值转换为“NSArray”
问题描述
我有一个来自服务器端的通知有效负载(Firebase 云消息传递),它由通常的userInfo和一个整数数组组成,我找不到将“records_id”键下的数组转换为[Int]的方法
这是我正在处理的userInfo的结构:
[
AnyHashable("title"): title,
AnyHashable("sound"): true,
AnyHashable("aps"): {
alert = {
body = "notif body";
title = "notif title";
};
"content-available" = 1;
"mutable-content" = 1;
sound = true;
},
AnyHashable("google.c.a.e"): 1,
AnyHashable("action"): stacked,
AnyHashable("record_id"): [61,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],
AnyHashable("gcm.message_id"): 1563172453549130,
AnyHashable("gcm.notification.fromAPI"): true,
AnyHashable("gcm.notification.action"): stacked,
AnyHashable("body"): notif body,
AnyHashable("gcm.notification.record_id"): [61,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],
AnyHashable("fromAPI"): true
]
这是我在AppDelegate中的代码:
// receive notification while app in foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
registerNotification(userInfo)
}
// register notifications records
func registerNotification(_ userInfo: [AnyHashable : Any]) {
print(userInfo) // this print the above userinfo structure that I show earlier
let ids = userInfo["record_id"] as! [Int]
for id in ids {
print("new record: \(id)")
}
}
上面的代码在尝试转换为[Int]时抛出以下错误:
Could not cast value of type '__NSCFString' (0x1bebadf60) to 'NSArray' (0x1bebae960).
解决方案
你可以试试
let userInfo = response.notification.request.content.userInfo
let ids = userInfo["records_id"] as! String
let res = try! JSONDecoder().decode([Int].self, from:Data(ids.utf8))
print(res)
推荐阅读
- android - (预计@AndroidEntryPoint 有一个值。你忘记应用Gradle 插件了吗?) 使用带有PESDK 的dagger hilt
- java - 如何以小写字母向后移动3个字母?
- vcl-styles - VCL 样式影响非 VCL 窗口
- r - 复杂的嵌套列表到R中的干净矩阵?
- javascript - JS / html游戏到Android应用程序而不使用webview
- javascript - 是否可以撤销网络推送通知
- php - 使用传递给 PHP 函数的 php 变量重复 HTML 元素
- kendo-react-ui - 条件多选数据
- stored-procedures - 如何在 Dapper 中插入后读取 SELECT
- sql - 使用 selectRaw 和 LIKE 的 SQL、Laravel 得分/排名结果?