Can Apple turn off push notifications, run my application in the background?

According to Apple's documentation, I can register for silent notification by adding the key "content-available" = 1 to the aps payload dictionary. I want my app to wake up in the background when a silent notification arrives. I set App downloads content in response to push notifications to Required background modes in my info.plist

This is my useful dictionary.

 {"aps": { "alert":"Notification alert","badge":1,"sound":"default","content-available":1 } } 

I get callbacks at -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler while my application is in the background. But my question is: can we get a callback to this or any other method when our application is in a state of death?

I do not want my application user to see a notification, but I want my application to perform a specific task, waking up in the background with silent notifications.

Any suggestions would be appreciated.

+5
source share
2 answers

When a device receives a push message with a set of content-available , your application launches Apple in the background. Users will not be aware of this. From the docs :

content-available : enter this key with a value of 1 to indicate that new content is available. Enabling this key and value means that when your application starts in the background or resumes, -application:didReceiveRemoteNotification:fetchCompletionHandler: called.

+4
source

I came across a similar scenario, I wrote this code for debugging if my application wakes up in a quiet notification or not.

 -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *str = [defaults objectForKey:@"key"]; if (str == nil) { str = @"didReceiveRemoteNotification"; }else{ str = [NSString stringWithFormat:@"%@, didReceiveRemoteNotification",str]; } [defaults setObject:str forKey:@"key"]; [defaults synchronize]; } 

This code works as if the application woke up, than you will receive a callback in this method, and the method name will be written in NSUserDefaults . Therefore, when you debug your application manually, you can see the str value of the string variable, if there was a line didReceiveRemoteNotification , than you know that your application woke up.

Note. This only works in the background for me. I get the value when I did not force my application to close (terminate manually), but when I close my application from the application switcher, I will not get any value.

I hope this works.

+4
source

Source: https://habr.com/ru/post/1238274/


All Articles