如何从userInfo通知将对象转换为Int对象?

时间:2019-06-01 12:09:52

标签: swift casting

我正在尝试解析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
    }

1 个答案:

答案 0 :(得分:1)

我怀疑您的价值不是真正的Int

您可以通过打印来调查基础类型:

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

您从评论中说,它返回了:__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
}