我想在收到推送通知后启动后台任务。到目前为止,我有以下内容:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSString* taskName = [NSString stringWithFormat:@"PushNotificationTask-%@", [[NSUUID UUID] UUIDString]];
NSLog(@"Starting bg-task for push notification %@", taskName);
self.pnBgTask = [application beginBackgroundTaskWithName:taskName expirationHandler:^{
NSLog(@"Expiring bg-task for push notification %@", taskName);
[application endBackgroundTask:self.pnBgTask];
self.pnBgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do work here
NSLog(@"Ending bg-task for push notification %@", taskName);
[application endBackgroundTask:self.pnBgTask];
self.pnBgTask = UIBackgroundTaskInvalid;
});
在前一个后台任务完成之前推送通知到达的情况下,此代码将失败,因为一个任务将覆盖另一个任务。
有人可以提出一个好的模式来解决这个问题吗?