简体   繁体   中英

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

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

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

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

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

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