Reputation: 135
Using the following code I am able to run my background app for around 180 seconds. My final objective is to keep it running forever. Battery/processor overuse is not a concern for me as I'm making this for myself.
This is code I'm using to run my app in the background.
UIApplication * application = [UIApplication sharedApplication];
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
NSLog(@"Multitasking Supported");
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
//To make the code block asynchronous
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
NSLog(@"Running in the background\n");
while(TRUE)
{
NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
[NSThread sleepForTimeInterval:1]; //wait for 1 sec
}
//#### background task ends
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});
}
else
{
NSLog(@"Multitasking Not Supported");
}
Background time remaining:
starts at around 180 seconds and by the time it comes down to 5, the app gets suspended. No matter what I try, this cannot be avoided.
My device is running iOS 8.1 and here are the methods I've tried so far:
Method 1:
I set background modes as location in info.plist and used the following code as shown in this tutorial.
CLLocationManager * manager = [CLLocationManager new];
__block UIBackgroundTaskIdentifier background_task;
and then
[manager startUpdatingLocation];
Method 2:
Using the following lines of code before the app enters the background state.
CLLocationManager* locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
I just need to reset backgroundTimeRemaining and any hack will be fine. Thank you all.
Upvotes: 0
Views: 2177
Reputation: 135
The way I solved this problem was following the updated part of this tutorial.
Upvotes: 1
Reputation: 25619
You can't keep it running in the background unless you have enabled 'Background app refresh' in your device's settings. beginBackgroundTaskWithExpirationHandler
is ment to be used for cleanup purposes:
This method lets your app continue to run for a period of time after it transitions to the background. You should call this method at times where leaving a task unfinished might be detrimental to your app’s user experience. For example, your app could call this method to ensure that had enough time to transfer an important file to a remote server or at least attempt to make the transfer and note any errors. You should not use this method simply to keep your app running after it moves to the background.
Upvotes: 1