简体   繁体   中英

How to handle push notification when app is in background but not suspended

My app receiving push notification, and showing appropriate info message for that. However when I'm clicking to the message, application becomes active but application didFinishLaunchingWithOptions is not getting called which is right i think, since the application is not suspended and it just resigns active. The question is how i can make sure that user clicked to message when application becomes to foreground ?

I think what you are looking for is this app delegate method:

- (void)application:(UIApplication *)application     
       didReceiveRemoteNotification:(NSDictionary *)userInfo

It will be called if your app is backgrounded, and the notification payload will be delivered in the userInfo dictionary. This contrasts with the situation when the app is launched from cold start, when this method does not get called, and instead you check in the launchOptions dictionary for the payload.

However the preferred way to do this since iOS7 is to use this:

- (void)application:(UIApplication *)application 
       didReceiveRemoteNotification:(NSDictionary *)userInfo 
             fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

This method is called when a user taps on a notification, regardless of whether the app is launched from cold start or foregrounded from background. So even if you are not using the completionHandler, it provides a more consistent way of accessing the notification payload. If this method is present, the older one does not get called.

If I understand the question correctly, you are asking how to be sure that the app was brought into the foreground as the result of the user “clicking” ie acting on a push notification .

When the app is not running at all, you can use -application:didFinishLaunchingWithOptions: as you mention. The launchOptions dictionary contains the payload, etc. — I won't describe this since you already know how this works.

When the app IS running however, that method is not going to be called. Instead, - application:didReceiveRemoteNotification: is called. BTW this is called if the app was already in the foreground OR if it was in the background and the user “clicked” on the push notification banner/alert to open the app. It will not be called otherwise: so I believe this is exactly what you're looking for.

The userInfo dictionary provided by this method will contain the notifications data, similarly to -application:didFinishLaunchingWithOptions: for more ad-hoc processing. (Note: userInfo and launchOptions are semantically different, but hopefully this is obvious. :))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM