I'm building an app with Swift that receives push notifications. I am sending custom values inside the JSON.
I am opening the app through the notification, so I know that I have to do this inside "didFinishLaunchingWithOptions" and read the value from "launchOptions".
How can I read those values and use them on my app.
Many thanks.
Here's what works for me in SWIFT 2 when your app is not launched. The code is not quite elegant because of the optional bindings. But it works.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// if launched from a tap on a notification
if let launchOptions = launchOptions {
if let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] {
if let action = userInfo["action"], id = userInfo["id"] {
let rootViewController = self.window!.rootViewController as! ViewController
let _ = setTimeout(5.0, block: { () -> Void in
rootViewController.openNotification(action as! String, id: id as! String)
})
}
}
}
return true
}
In the application:didReceiveRemoteNotification:fetchCompletionHandler, The custom data is in passed on to the didReceiveRemoteNotification, which is an NSDictionary. The details that you want to retrieve is probably on the "aps" key of the userInfo.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary!)
{
var notificationDetails: NSDictionary = userInfo.objectForKey("aps") as NSDictionary
}
When the app is not launched, you will need to get it from the application:didFinishedLaunchWithOptions,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
if let launchOpts = launchOptions {
var notificationDetails: NSDictionary = launchOpts.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary
}
return true
}
EDIT: Remote Notification Fix syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With