Background Task with NSOperation and NSOperationQu

2020-04-26 23:41发布

I want to upload some files which should continue even if the application goes into background.

Currently I am retrieving the files from the DB and than adding it to the Queue via NSOperation which is then starts the upload procedure.

All the files should be uploaded even if the app goes to background or foreground. Below is the code for single task can anyone give me a hint how we can make it to work for uploading many files.

UIApplication* application = [UIApplication sharedApplication];
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  // Clean up any unfinished task business by marking where you
  // stopped or ending the task outright.

  [application endBackgroundTask: bgTask];
  bgTask = UIBackgroundTaskInvalid;
}];

2条回答
看我几分像从前
2楼-- · 2020-04-27 00:14

Why not try doing this? .. I haven't yet tried it out, I'll post an update after attempting this

UIApplication* application = [UIApplication sharedApplication];
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  // Clean up any unfinished task business by marking where you
  // stopped or ending the task outright.

  // Bring up your NSOperation queue instance here and block this thread until it is complete
  [queue waitUntilAllOperationsAreFinished];

  [application endBackgroundTask: bgTask];
  bgTask = UIBackgroundTaskInvalid;
}]; 

also ensure that you have a way to cancel all these long standing operation in the background

 bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you.
        // stopped or ending the task outright.
        [queue cancelAllOperations];

        [application endBackgroundTask:endSessionTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
查看更多
一夜七次
3楼-- · 2020-04-27 00:17

Apple allows background execution if your app follows and satisfy the necessary condition. plese refer here

查看更多
登录 后发表回答