【问题标题】:How can I cast to Int an object from userInfo notification?如何从 userInfo 通知转换为 Int 对象?
【发布时间】:2019-06-01 12:09:51
【问题描述】:

我正在尝试解析 gcm.notification.createdAt 键,但它的值没有被转换为 Int。 奇怪的是,即使值类型显然是Int,它也不起作用,正如您所看到的。 知道我在这里做错了什么吗?

userInfo is [AnyHashable("gcm.notification.chatUID"): -LgHYXKFNmP-mQo7s9nB, 
             AnyHashable("gcm.notification.type"): chat, 
             AnyHashable("gcm.notification.createdAt"): 1559389303, 
             AnyHashable("google.c.a.e"): 1, 
             AnyHashable("gcm.message_id"): 0:1559389316529351%e413fc3ee413fc3e, 
             AnyHashable("aps"): {
    alert =     {
        body = "You have a new message";
        title = "New Message from Lehz Raus";
    };
    badge = 1;
    sound = default;
}]

let userInfo =  response.notification.request.content.userInfo

guard let createdAt = userInfo["gcm.notification.createdAt"] as? Int else {
            print("gcm.notification.createdAt is not showing")
            return
           }

 //this works as expected
    guard let chatUUUUID = userInfo["gcm.notification.chatUID"] as? String else {
        print("no chatUUUUID printed")
        return
    }

【问题讨论】:

  • print(type(of: userInfo["gcm.notification.createdAt"])) 打印什么?
  • 试试userInfo[AnyHashable("gcm.notification.createdAt")]
  • @vacawama 它打印Optional<Any> (lldb)
  • 好的,打开它:print(type(of: userInfo["gcm.notification.createdAt"]!)) 打印什么?
  • @vacawama ` __NSCFString (lldb) ` 从服务器发送它时,它看起来像转换为字符串。我不知道为什么,因为我已经检查了三倍,并且在服务器上它作为 Int 发送

标签: swift casting


【解决方案1】:

我怀疑你的值并不是真正的Int

您可以通过打印来调查底层类型:

print(type(of: userInfo["gcm.notification.createdAt"]!))

从 cmets 中,您说它返回了:__NSCFString,所以服务器给了您一个 String。您可以将其转换为 Int,并在您的 guard 语句中添加一行:

guard let createdAt = userInfo["gcm.notification.createdAt"] as? String,
      let createdAtInt = Int(createdAt) else {
    print("gcm.notification.createdAt is not showing")
    return
}

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多