Reputation: 313
My App uses Apple push notification service. When my App is not in foreground and if I receive a push notification, the notification will be shown in the Notification banner. When we tap on that notification, App will resume and will execute some lines of code by application:didReceiveRemoteNotification:
method.If the user did not see this notification in the banner, and directly launch the app by its icon, application:didReceiveRemoteNotification:
method won’t be called. Then, how can I execute those lines of code? I need to execute those lines of code instantly when App receives notification regardless of the state of the App. How it is possible?
Upvotes: 0
Views: 233
Reputation: 123
Until unless you click the notification, app will not know that notification is received. So, create a separate method for that block of code and call it from application:didReceiveRemoteNotification:
if you are using badge numbers. save the badge numbers in NSUserDefaults and when app is launched from the app icon. Compare the badge numbers with previous once add call the block of which you want to execute from didFinishLaunchingWithOptions:
Upvotes: 0
Reputation: 23624
The short answer to this is that you can't, at least not using just the push notification service. If the user did not open the app by tapping the notification, you cannot see what notifications have been received, if any.
There are a few things you can try though.
If your push notification also increments the badge number on the app icon, you can access that using [UIApplication sharedApplication].applicationIconBadgeNumber
. If the number is anything but 0 this would tell you how many push notifications were received (but not which ones, if you have different ones). Remember to clear this number when appropriate.
If you are using a backend service, you can also keep track of what push notifications have been sent out on that end, and request that information in your app when it becomes active.
The right answer here though is probably to rework how you are architecting your app so that this is not a requirement, and instead just refresh whatever data needs to be refreshed when your app becomes active, regardless of whether a push notification was received or not.
Upvotes: 1
Reputation: 17409
In the UIApplicationDelegate
protocol there’s application:didFinishLaunchingWithOptions:
.
If your app is launched by the user tapping the right button in an alert of a push notification, the launchOptions
dictionary bound to the method call will contain information regarding that notification;
if your app is already running then application:didReceiveRemoteNotification:
(also in the delegate protocol) will get called instead.
Upvotes: 0