When receiving a remote push notification as the application is in the background, the app enters applicationDidBecomeActive. From there, how can I access the NSDictionary of data from the notification?
The notification data is delivered to your app in application:didReceiveRemoteNotification:
. If you want to process it in applicationDidBecomeActive:
you should store it in application:didReceiveRemoteNotification:
and read it again in applicationDidBecomeActive
.
application:didReceiveRemoteNotification:
you can query -[UIApplication applicationState]
to find out if your app is already in the foreground. If it is then just process the notification right away. –
Recitativo Swift version:
var dUserInfo: [NSObject : AnyObject]?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// code...
if let info = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
dUserInfo = info
}
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
dUserInfo = userInfo
}
func applicationDidBecomeActive(application: UIApplication) {
// code...
self.yourAction(dUserInfo)
}
func yourAction(userInfo: [NSObject : AnyObject]?) {
if let info = userInfo?["aps"] as? Dictionary<String, AnyObject> {
}
}
I use this code to manage the push:
In the AppDelegate
@implementation AppDelegate{
NSDictionary *dUserInfo; //To storage the push data
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Check for options
if (launchOptions != nil)
{
//Store the data from the push.
dUserInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dUserInfo != nil)
{
//Do whatever you need
}
}
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
//Data from the push.
if (dUserInfo != nil)
{
//Do whatever you need
}
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//Store the data from the push.
if (userInfo != nil)
{
dUserInfo = userInfo;
}
}
I hope this will be useful for someone.
Happy coding.
If your app is in background
state when push notification is received and tapped, the app will get invoked with application:didFinishLaunchingWithOptions:
and not application:didReceiveRemoteNotification:
.
Push notification payload can be accessed in application:didFinishLaunchingWithOptions:
from launchOptions
dictionary.
© 2022 - 2024 — McMap. All rights reserved.