开发者

How do I access remote push notification data on applicationDidBecomeActive?

When receiving a remote push notification as the application is in the background, the app enter开发者_如何学编程s 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜