首页 > 解决方案 > 无法将“__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).

标签: iosswiftfirebase-cloud-messaging

解决方案


你可以试试

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)

推荐阅读