How to use beginBackgroundTaskWithExpirationHandler for already running task in iOS

前端 未结 6 1513
悲哀的现实
悲哀的现实 2020-11-28 03:10

In my app, I am uploading images to server from iPhone. While sync if user press home button, App will close.

I want app must be running in background till sync fini

6条回答
  •  情歌与酒
    2020-11-28 04:17

    Here's how I used beginBackgroundTaskWithExpirationHandler, including the call to the method to be done in the background. This includes code for starting the new async task. So not exactly what is asked in the question. Adding code below, thinking someone might be looking for this scenario:

    - (void)didReceiveObjList:(CFDataRef)message
    {
      // Received Object List. Processing the list can take a few seconds.
      // So doing it in separate thread with expiration handler to ensure it gets some time to do     the task even if the app goes to background.
    
      UIApplication *application = [UIApplication sharedApplication];
      __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          [self processObjList:message];
    
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
      });
    
      NSLog(@"Main Thread proceeding...");
    
    }
    

提交回复
热议问题