Prashant Sharma
Prashant Sharma

Reputation: 1407

How to fetch data from push notification when app is turned off?

I want to fetch data from push notification when app is turned off. I am using the following code given below:

- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
{
    NSDictionary *aps = userInfo[@”aps”];

    if (state == UIApplicationStateInactive){
    // user tapped notification
         NSLog(@"results%@",aps);
         completionHandler(UIBackgroundFetchResultNewData);
    } else {
    // app is active             
         completionHandler(UIBackgroundFetchResultNoData);
    }
}

In above code NSLog(@"results%@",aps); doesn't get print the values when app is in background. Please Help me out

Upvotes: 2

Views: 834

Answers (3)

Hasya
Hasya

Reputation: 9898

didReceiveRemoteNotification works only when you tap on notification. so it will provide you data only when you tap on notification and your app will get open.

If you want to get NSDictionary *aps = userInfo[@”aps”]; when your app is in kill state, then you have to implement pushkit framework.

You can download sample code from 1 my answer

Can someone share a sample code of iOS Xamarin PushKit in C#?

Register for voip notifications outside of app delegate

Source https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Upvotes: 3

Prashant Sharma
Prashant Sharma

Reputation: 1407

Sample change from server end that done the trick for me.

{
    aps = {
        "content-available" : 1,
        sound : ""
    };
}

Upvotes: 0

Rakshith Nandish
Rakshith Nandish

Reputation: 639

When is app is turned off or terminated to be precise , didReceiveRemoteNotification is not called for obvious reasons Appdelegate's didFinishLaunchingWithOptions launchOptions provides a solution for this. The Launchoptions is basically a dictionary to tell the app in which way it was launched.For your implementation you need to check if launchOptions has any value in the key UIApplicationLaunchOptionsRemoteNotificationKey, like so ()

let userInfo = launchOptionForApp[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary

your userInfo dictionary has the json you will need to parse and implement your further logic

Upvotes: 0

Related Questions