iOS Push Notification - How to get the notification data when you click on the app icon instead of notification

守給你的承諾、 提交于 2019-11-27 17:27:20

You can't get remote push payload by launching app from homescreen.

If the push data is important for app use, load it from your server after app launched.

@fannheyward answer is absolutely correct. You cannot get payload when application is launched by tapping app icon.

I have an idea, what if you get to know that some notification is pending when app is launched by tapping app icon. With this knowledge your app can fetch payload from your server.

You can set "Badge" in every such notification and on applicationDidBecomeActive you can check [application applicationIconBadgeNumber] > 0 to know that some notification is active. After fetching payload from your server you can set it to 0 like below

[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

Please note: This means your app will have badge displayed over it when notification is received. I am not sure of the behaviour when badge is disabled by user from settings.

kasajei

If your application target is over iOS7, you can do only if application is alive in backgroud.

In the capabilities settings at Xcode, you should enable Background Modes>Remote notifications, and write below code.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{ 
    // save userInfo in NSUserDefaults
    completionHandler( UIBackgroundFetchResultNoData );
}

If you want to test it, it will be helpful to use https://github.com/acoomans/SimulatorRemoteNotifications

  • From the server side, make sure to set content-available property with a value of 1

For this to work I also had to check the background fetch box.

You should get the notification in the launchWithOptions method in your appDelegate something like this:

NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];   

    if(remoteNotif != nil){  
        //Handle your notification   
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!