Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a finite-length background task

Tags:

ios

ios6

ios4

ios5


I am doing some processing when the app enters the background state, I have put it under the beginBackgroundTaskWithExpirationHandler() and thereby, should be allotted ten minutes for the same. However, I believe the app is being suspended before that. The task I am performing is memory and CPU-intensive, so is it possible that the OS is putting my app to suspend state ?
If so, is there any way to bypass these restrictions. (I am open to using private API's).

Here is the code for starting the background task:

   if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){

        if([[UIDevice currentDevice] isMultitaskingSupported]){
            __block UIBackgroundTaskIdentifier bgTask;
            UIApplication *application = [UIApplication sharedApplication];
            bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

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

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [self captureImage];
                [application endBackgroundTask:bgTask];
                bgTask = UIBackgroundTaskInvalid;
            });
        }
    }
like image 388
Hrishikesh_Pardeshi Avatar asked Oct 22 '22 22:10

Hrishikesh_Pardeshi


1 Answers

I am not sure that Daij-Dan is completely right.

This part I agree with him:

the os may kill you at any time when its pressured.

However word "pressured" is quite vague. And I believe there should be a lot of pressure (low memory as example) to suspend app which legitimately requested more time. On one hand, it's a real scenario case. On other hand, it's happening not that often (iOS devices have quite a lot of memory nowdays).

From documentation (http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html):

Each call to this method must be balanced by a matching call to the endBackgroundTask: method. Applications running background tasks have a finite amount of time in which to run them. (You can find out how much time is available using the backgroundTimeRemaining property.) If you do not call endBackgroundTask: for each task before time expires, the system kills the application. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.

I would recommend:

  • Add some logs in completion handler
  • Add logs to the logs with logic (including backgroundTimeremaining)

And if your app got suspended review system console logs.

P.S. I removed iphone-privateapi tag, since it's public API.

like image 137
Victor Ronin Avatar answered Oct 27 '22 22:10

Victor Ronin