简体   繁体   中英

access value for dictionary key in swift

I am having a problem with accessing the value of the key alert in [AnyHashable("aps")]. I am trying to store the notification alert into a string so I can do further actions, but I was not able to access the alert value. Do you guys know what I am doing wrong?

I am new to swift and trying to get my hands dirty through building my own app. I appreciate your help guys!

func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    completionHandler([.sound, .alert])
}

actual output:

[
    AnyHashable("gcm.message_id"): 0:1559231429586204%16146ddd16146ddd,
    AnyHashable("google.c.a.ts"): 1559231429,
    AnyHashable("aps"): {
        alert = "BBQ event on 6/15";
        sound = enabled;
    },
    AnyHashable("gcm.n.e"): 1,
    AnyHashable("google.c.a.udt"): 0,
    AnyHashable("gcm.notification.sound2"): enabled,
    AnyHashable("google.c.a.e"): 1,
    AnyHashable("google.c.a.c_id"): 5464147931275974726
]

expected output:

"BBQ event on 6/15"

You need to first fetch value of aps as Dictionary of type [AnyHashable:Any] . Then get the value of alert from apsDict , ie

if let apsDict = userInfo["aps"] as? [AnyHashable:Any] {
    if let alert = apsDict["alert"] {
        print("Alert: \(alert)")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM