问题
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?
回答1:
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
.
回答2:
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> {
}
}
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/6732427/how-do-i-access-remote-push-notification-data-on-applicationdidbecomeactive