Can Apple's silent push notifications launch my app in the background?

别等时光非礼了梦想. 提交于 2019-11-30 21:58:27
TwoStraws

When the device receives a push message with content-available set, your app gets launched in the background by Apple. Users won't be aware of it. From the docs:

content-available: Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed, -application:didReceiveRemoteNotification:fetchCompletionHandler: is called.

Also from docs

didReceiveRemoteNotification: However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.

I have faced a similar kind of scenario, I wrote this code to debug if my application is waking up on silent 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 like, if you app wakes up than you'll get callback in this method and the method name will be written in NSUserDefaults. So when you debug your app manually you can see the value of str string variable, if there is string didReceiveRemoteNotification than you'll get to know that you application has woke up.

Note: This works only in background mode for me. I get value when I did not force close(terminate manually) my app but when I force close my app from app switcher I'll not get any value.

I hope that works.

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