bibscy
bibscy

Reputation: 2708

How can I cast to Int an object from userInfo notification?

I am trying to parse gcm.notification.createdAt key, but its value is not being casted as Int. Strangely it is not working even though the value type is clearly Int as you can see. Any idea what am I doing wrong here?

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
    }

Upvotes: 0

Views: 556

Answers (1)

vacawama
vacawama

Reputation: 154603

I suspect your value is not really an Int.

You can investigate the underlying type by printing:

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

From the comments, you said it returned: __NSCFString so the server is giving you a String. You can convert that to an Int with an additional line in your guard statement:

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

Upvotes: 1

Related Questions