Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift read userInfo of remote notification

I implemented a function to open an AlertView when I receive a remote notification like this:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){         var notifiAlert = UIAlertView()         var NotificationMessage : AnyObject? =  userInfo["alert"]         notifiAlert.title = "TITLE"         notifiAlert.message = NotificationMessage as? String         notifiAlert.addButtonWithTitle("OK")         notifiAlert.show() } 

But NotificationMessage is always nil.

My json payload looks like this:

{"aps":{"alert":"Testmessage","badge":"1"}} 

I am using Xcode 6, Swift and I am developing for iOS8. I searched hours now, but didn't find any useful information. The Notifications works perfectly.. and if I click it, the alertview opens. My problem is, that I am not able to get the data out of userInfo.

like image 716
0x52 Avatar asked Feb 18 '15 23:02

0x52


2 Answers

The root level item of the userInfo dictionary is "aps", not "alert".

Try the following:

if let aps = userInfo["aps"] as? NSDictionary {     if let alert = aps["alert"] as? NSDictionary {         if let message = alert["message"] as? NSString {            //Do stuff         }     } else if let alert = aps["alert"] as? NSString {         //Do stuff     } } 

See Push Notification Documentation

like image 164
Craig Stanford Avatar answered Sep 21 '22 12:09

Craig Stanford


Swift 5

struct Push: Decodable {     let aps: APS          struct APS: Decodable {         let alert: Alert                  struct Alert: Decodable {             let title: String             let body: String         }     }          init(decoding userInfo: [AnyHashable : Any]) throws {         let data = try JSONSerialization.data(withJSONObject: userInfo, options: .prettyPrinted)         self = try JSONDecoder().decode(Push.self, from: data)     } } 

Usage:

guard let push = try? Push(decoding: userInfo) else { return } let alert = UIAlertController(title: push.aps.alert.title, message: push.aps.alert.body, preferredStyle: .alert) 
like image 26
Alexander Algashev Avatar answered Sep 18 '22 12:09

Alexander Algashev