I am writing an iOS app which sync data. I need sync service to run when app is in background as well. So I've written this piece of code in the place where I am uploading data.
- (void)startAsyncUpload {
UIApplication *thisApplication = [UIApplication sharedApplication];
if([thisApplication respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) {
bgTaskIdentifier_ = [thisApplication beginBackgroundTaskWithExpirationHandler:^(void)
{
[thisApplication endBackgroundTask:bgTaskIdentifier_];
bgTaskIdentifier_ = UIBackgroundTaskInvalid;
}];
}
[self multipartUpload];}
It works fine and run in background. But I've a problem here. I was uploading a video file and when my background time expired the handler was called and it ended the task. Now when I came to foreground again uploading resumed, fine. But now when I went to background again it's not resuming the background task.
I know why, basically because I ended the task before. But is there any way to resume the task again, something like registering the task again for background running?
Are you sure you are calling beginBackgroundTaskWithExpirationHandler: for the second time?
Create one ivar/property for bgTaskIdentifier and one for a BOOL isUploading. Then you could write a method like this
- (void)resumeOrStartAsyncLoad
{
if(!self.isUploading)
{
[self multipartUpload];
self.isUploading = TRUE;
}
if(self.isUploading && self.bgTaskIdentifier == UIBackgroundTaskInvalid)
{
UIApplication *thisApplication = [UIApplication sharedApplication];
self.bgTaskIdentifier = [thisApplication beginBackgroundTaskWithExpirationHandler:^(void) {
[thisApplication endBackgroundTask:bgTaskIdentifier_];
bgTaskIdentifier_ = UIBackgroundTaskInvalid;
}];
}
}