iOS 8 push notification action buttons - code in handleActionWithIdentifier does not always run when app is in background

梦想的初衷 提交于 2019-12-03 01:48:10

I have finally figured out the reason. The fact that it sometimes works and sometimes doesn't should have given me the hint much sooner.

According to the Apple documentation of application:handleActionWithIdentifier:forRemoteNotification:completionHandler::

Your implementation of this method should perform the action associated with the specified identifier and execute the block in the completionHandler parameter as soon as you are done. Failure to execute the completion handler block at the end of your implementation will cause your app to be terminated.

I am calling the completion handler at the end of the application:handleActionWithIdentifier:forRemoteNotification:completionHandler method. However, the fact that I am sending requests to the server in my handler code means that my end of implementation is not simply at the end of the method; my real end lies within the callback of my requests. The way I code it, completion handler and callback are on two different threads, and when completion handler runs before it reaches callback, it'll fail.

So the solution is to move the completion handler into the callback methods of the request, i.e., the real "end of the implementation". Something like this:

[MyClient sendRequest:userInfo withSuccessBlock:^(id responseObject){
    NSLog(@"Accept - Success");
    if (completionHandler) {
        completionHandler();
    }
} withFailureBlock:^(NSError *error, NSString *responseString) {
    NSLog(@"Accept - Failure: %@",[error description]);
    if (completionHandler) {
        completionHandler();
    }
}];

On iOS8 you need to call

[application registerForRemoteNotifications];

from application:didRegisterUserNotificationSettings::

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    [application registerForRemoteNotifications];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!