Mike Mike - 15 days ago 11
iOS Question

Swift 3 Get Notification Data

I'm trying to get the data out of a notification in swift 3, using this tutorial: Developing Push Notifications for iOS 10 Unfortunately I get the following error:

private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) {
let aps = notification["aps"] as? [String:AnyObject]
let alert = aps["alert"] as? [String:AnyObject]
let title = alert?["title"] as? String
let body = alert?["body"] as? String
return (title ?? "-", body ?? "-")
}


enter image description here

Answer

The issue is that notification is declared as a dictionary with keys of type NSObject. But you attempt to access that dictionary with a key of type String. String is not an NSObject. One solution is to cast your String to NSString.

Fixing that presents another error which is fixed on the next line. So your code ends up like this:

private func getAlert(notification: [NSObject:AnyObject]) -> (String, String) {
    let aps = notification["aps" as NSString] as? [String:AnyObject]
    let alert = aps?["alert"] as? [String:AnyObject]
    let title = alert?["title"] as? String
    let body = alert?["body"] as? String
    return (title ?? "-", body ?? "-")
}

Having said all of that, that tutorial has a lot of mistakes and uses the wrong parameter types in many places. This getAlert method should not be using NSObject. It should be String.

Comments