iOS Do Scheduled Operation in Background or When App Active

iOS do scheduled operation in background or when app active

There is no way to execute a function at regular intervals, even when the app is backgrounded/killed by the user.

The most reliable solution for executing a function at regular intervals even when the app is backgrounded is to use push notifications scheduled for the specific time intervals (midnight each day in your case), which would wake up the app and let it update its data. However, this solution has its downsides, since you need a server to send the push notification from and the users device needs to be connected to the internet. Also, push notifications don't wake up the app in case the user manually killed it.

For your particular problem, the best solution would be to refactor your code in a way that you have a single function that can be used to retrieve data and hence this function could ensure the data is updated in case a certain time interval has passed since the last update.

iOS: Repeated task only when APP is active (No background)

Here is some code on how to achieve this with a timer and both GCD and an operation queue.

NSOperationQueue* queue = [NSOperationQueue new];
[queue setMaxConcurrentOperationCount:1]; //Make serial.
//dispatch_queue_t queue = dispatch_queue_create("queue", NULL); //Serial queue.

Gentlemen, start your timers:

[NSTimer scheduledTimerWithTimeInterval:0.0 target:appDelegate selector:@selector(timerTicked:) userInfo:nil repeats:NO]; //Start a timer with 0 so it ticks immediately.

Now in the method:

- (void)timerTicked:(NSTimer*)timer
{
NSLog(@"Timer ticked!");
void (^block)() = ^{
//Do what you need here.

//Start a new timer.
[NSTimer scheduledTimerWithTimeInterval:1.0 target:appDelegate selector:@selector(timerTicked:) userInfo:nil repeats:NO];
};

[queue addOperationWithBlock:block];
//dispatch_async(queue, block);
}

I use the app delegate because timers retain the target object, so I don't want to have it in a view controller. You can schedule the next timer either right after timer tick or after the operation/task has completed, which is what I prefer to do.

Running a background task in iOS at a specific time in the future

any purely on-device - unfortunately till now - 2014 there is no such ways. Background task execution if content avaliable appeared in iOS 7 is rather a good thing but it is push-based.

So when the app is suspended it cannot do ANYTHING to rouse itself directly. It cannot previously have scheduled an NSTimer, it cannot make use of something like performSelector:afterDelay and so on and so forth. The ONLY way the app can become active again is if the USER HIMSELF does something to make it active e.g local notification received and an alert poped up. Execution of an app in background mode for a long time is only allowed when an app has a background mode, theses modes are: voip, audio, location, newstand. Note: Starting in iOS 9, kCFStreamNetworkServiceTypeVoIP is deprecated now, and VoIP apps should use PushKit instead (VoIP high-prioirity push notifications). Even if it has one of these types an application cannot execute its code without some restrictions. You can read about it in the docs. So we have to accept this status of affairs. May be some time in a future Apple engineers will make a true multitasking or at least something like background task execution on local notification received or some global background tasks sheduler for all the apps installed. But I don't believe in this, because limited background execution of 3-rd party processes is a core design of iOS scheduler, which is a modified version of CMU Mach 3 scheduler.

Perform background tasks when app is terminated

You have two options

  1. Background App Refresh
  2. Silent push notifications

Easiest one is Background App Refresh. Because later one needs a server to send the notification. You can check following API for the usage. Basically you set Background Fetch capability on Capabilities/Background Modes of your app. Then from time to time, iOS will wake up your app and call application(_:performFetchWithCompletionHandler:) delegate. You will have around 30-45 seconds to call your function and call completion handler. If you don't finish it on time, iOS will kill your app. If you don't obey the rules, iOS will give you less chances to wake up. For more detailed usage of Background Modes, you may check following tutorial

Run app for more than 10 minutes in background

See "Background Execution" section of the iPhoneAppProgrammingGuide. In short, your app must be one of these types:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Newsstand apps that need to download and process new content
  • Apps that receive regular updates from external accessories

And you must add to the Info.plist as follows:
Add the UIBackgroundModes key to your
Info.plist file and set its value to an array containing one or more of the following strings:

  • audio—The app plays audible content to the user while in the background. (This content includes streaming audio or video content using AirPlay.)
  • location—The app keeps users informed of their location, even while it is running in the background.
  • voip—The app provides the ability for the user to make phone calls using an Internet connection.
  • newsstand-content—The app is aNewsstand app that downloads and processesmagazine or newspaper
    content in the background.
  • external-accessory—The app works with a hardware accessory that needs to deliver updates on a
    regular schedule through the External Accessory framework.
  • bluetooth-central—The app works with a Bluetooth accessory that needs to deliver updates on a
    regular schedule through the CoreBluetooth framework

Note that part of the review process will be checking to make sure that your app does what it says it's doing with regard to background processing.



Related Topics



Leave a reply



Submit