iOS Application Executing Tasks in Background

iOS application executing tasks in background

Building on what rckoenes stated, applications are allowed to register background tasks to be completed after the user hits the home button. There is a time limit of 10 or 15 minutes for these tasks to complete. Again, you can register a task to complete immediately after the user hits home, this does NOT allow you to execute code say an hour after they exit the app.

UIApplication*    app = [UIApplication sharedApplication];
task = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// Do the work associated with the task.
NSLog(@"Started background task timeremaining = %f", [app backgroundTimeRemaining]);
if (connectedToNetwork) {
// do work son...
}

[app endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
});

UPDATE: if your app supports versions of iOS previous to iOs 4, you should also check to ensure that multitasking is supported before registering a background task. Use something along the lines of:

UIDevice* device = [UIDevice currentDevice];

BOOL backgroundSupported = NO;

if ([device respondsToSelector:@selector(isMultitaskingSupported)])

backgroundSupported = device.multitaskingSupported;

How long does Apple permit a background task to run?

Correct me if I am wrong, but I have stumbled upon a perfect article from Xamarin that discusses iOS backgrounding feature.

I will simply break down to two parts, ios pre 7 and ios 7+:

iOS version pre 7

The answer is simply 600 seconds (10 minutes), reason is provided by
the article above.

iOS version 7+

The answer is that the time system allocates you is opportunistic. You
will have to use @Gary Riches's suggestion

NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);

to find out. The reason for it being opportunistic is the way iOS 7+
handles background tasks is completely different, certainly optimised. To
be exact, It has an intermittent behaviour, and therefore, if you need
background tasks such as downloading a big chuck of data, it will be
much more effective if you use `NSURLSession` instead.

However, in my special case, I am uploading one single object that contains one file to be exact. I do not have to consider NSURLSession for uploading a small amount of data. And besides, it's uploading task, it can take as much time as it wants. :-)

For these TL;DR visitors, the answer above should be sufficient. For more details, please refer to the article above.

Run task in background mode in iOS

It's possible only if your app has background mode enabled and it's in the background state. Background state is reached when user exit from your application and until garbage collector doesn't kill it for memory usage.

If you're goal is to download something every day / week / month in background even if user doesn't use app, that's impossible on iOS.

How to do some task in background after kill the application

There is no way to run any kind of processes in the background after user kills the application. See what Viber does for their app.

Sample Image

So you can give a notice to user not to quit the app, but you would have to give them a valid reason. And if your app is not GPS or Music app your app will not be active in the background and you all your processes will be suspended by the OS to save battery life.

How to get your iOS app to run in the background for longer than 3 minutes?

We haven’t had the old 10 minute window for years so that is simply no longer applicable. That was reduced to 3 minutes in OS 7, and further reduced to 30 seconds in iOS 13. (There is a new concept of background tasks, for running tasks longer than 30 seconds, but the the OS will run these at its own discretion, e.g. at night, when the user is charging their device, so that’s not really applicable here).

The short answer to your question is that you cannot submit apps to the store that run in the background indefinitely unless it’s one of a very limited list of permitted background modes.

If you can go to the “Signing & Capabilities” tab of your target and add “Background Modes” and you can see the list of alternatives:

Sample Image

So, with the caveat that you cannot do precisely what you asked, here are a few observations:

  1. The “External accessory communication” background mode (see ExternalAccessory) seems promising, but that’s for bluetooth or wired connections only. So unless you can refactor/reengineer how your devices communicates, that is likely not a viable solution.

  2. There’s an interesting question of whether just keeping the app running in the foreground might be helpful (e.g. judicious use of idleTimerDisabled). I know this solves a different problem (and should be used only where essential), but perhaps it’s option for you.

  3. If your external device is Internet-enabled and you want it to inform the app of some event, perhaps you can have it communicate its intent to some web service that then triggers an APNS push notification that your device can receive.

Bottom line, you can’t do what you ask, but if you edit your question with more details about the nature of the device and what your iOS app wants to do with that device, we might be able to provide better counsel. But in answer to the general question “can I just keep app running perpetually in the background”, the answer is “no.”

iOS app to run continuously in background

For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that record audio content while in the background
  • Ap ps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Apps that need to download and process new content regularly
  • Apps that receive regular updates from external accessories
  • Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services.

Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.

Background tasks on IOS 13 (BGTaskScheduler)

No , After restarting the device or after killing the app manually , no Background Task will be executed or start again automatically.

It is because then the State of Your App will be Changed

Various methods of AppDelegate are given in the Apple Docs , which handles different States of the App (ForeGround/BackGround/Terminated etc.)

  1. If you manually kill your app then applicationWillTerminate(_ application: UIApplication) will be executed in your AppDelegate.swift file (So , you can set some action to perform which will be executed just before app will be manually killed.)

Note that when it executes Your any BackGround Task will also be terminated & the State of your app is changed from BackGround -> Terminated


  1. When we Switch off or Restart the device , It is an external event and has nothing to do with your app, So we are not able to determine the State of the App

Even if your App is in the Back-Ground and performing any BGTask , if device will be switching off , App won't even execute applicationWillTerminate or any AppDelegate method

How to run operations in background while an iOS application is in foreground

Review the Background Execution portion of Apple's App Programming Guide for iOS.

UIApplication provides an interface to start and end background tasks with UIBackgroundTaskIdentifier.

In the top level of your AppDelegate, create a class-level task identifier:

var backgroundTask = UIBackgroundTaskInvalid

Now, create your task with the operation you wish to complete, and implement the error case where your task did not complete before it expired:

backgroundTask = application.beginBackgroundTaskWithName("MyBackgroundTask") {
// This expirationHandler is called when your task expired
// Cleanup the task here, remove objects from memory, etc

application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}

// Implement the operation of your task as background task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Begin your upload and clean up JSON
// NSURLSession, AlamoFire, etc

// On completion, end your task
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}


Related Topics



Leave a reply



Submit