Background application execution in iOS 13

The main event of the year in the world of iOS and MacOS developers, WWDC, invariably pleases all people involved in the industry with the release of new versions of the operating system, frameworks, hardware - in general, all that actually needs to be worked on.



This year was no exception and the subject of active discussion was the new version of iOS, SwiftUI, and the own iPadOS OS for you-yourself-understood-what-devices.



However, there were topics that were less covered, but no less interesting from this - for example, such a useful thing as the background execution of applications was touched.



Briefly about the topic



For those who do not quite understand what Background execution is, let’s explain: execution in the background means the application is doing some work in a state when it is not physically running on the user's smartphone screen (i.e. is not in foreground) .



image



This picture clearly shows in what conditions the application can stay and how to get from one to another.



Also, Apple developers in this session focused on the consumption of resources (I hope it is quite obvious that when working in the background, the application continues to consume energy). But it's time to go directly to the report.



What happened at WWDC



Actually, the speakers began with the same thing as I did - briefly talked about working in the background and described the tasks that would be performed there.



image



We are moving closer to development. There are 3 main Apple considerations when it comes to background performance:





Everything is quite simple - if an application task is running in the background, this execution can occur while another application is running in the foreground. Thus, there is a resource restriction placed on you to ensure that resources will not be excessively consumed. If these limits are exceeded, your application may be forcibly terminated by Apple, which will slow down further startup time. As for privacy, the company strongly recommends that developers use all the features of their API to inform the user about what data the application uses in its work (even in the background).



By the way, the list of these APIs was pretty impressive - they didn’t do a separate review, but I advise you to pay attention to them.



Yes, and at the session itself, Apple developers showed a brief overview of the possibilities using the messenger application example (it’s worth watching a video from WWDC).



BackgroundTasks



Almost half of the report this year is dedicated to this framework.



2 types of tasks that this novelty provides:





App Refresh Task



BG App Refresh Task is a special type of background task that we can use to update application data. One thing that makes this type of task very special is user behavior. iOS learns how often and at what time the user launches your application, and tries to launch BGAppRefreshTask at a time when the user is unlikely to use the application.



image



Yes, it will not work longer than 30 seconds - the feature is very unpleasant, left over from previous versions of the OS.



Consider an example of code from the Internet.



import UIKit import BackgroundTasks @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { BGTaskScheduler.shared.register( forTaskWithIdentifier: "pl.snowdog.example.refresh", using: DispatchQueue.global() ) { task in self.handleAppRefresh(task) } return true } private func handleAppRefresh(_ task: BGTask) { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 let appRefreshOperation = AppRefreshOperation() queue.addOperation(appRefreshOperation) task.expirationHandler = { queue.cancelAllOperations() } let lastOperation = queue.operations.last lastOperation?.completionBlock = { task.setTaskCompleted(success: !(lastOperation?.isCancelled ?? false)) } scheduleAppRefresh() } }
      
      





There are several points that you need to stop and consider better:





Background Processing Task



Another type of background hack is the BG Processing Task. You can use it to train the ML model on the device or do a cleanup in the database. Apple promises that the system is able to allocate up to several minutes of time for this type of task, which is a very important innovation for heavy work that does not fit into a miserable 30 seconds.



Again an example:



 import UIKit import BackgroundTasks @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { BGTaskScheduler.shared.register( forTaskWithIdentifier: "pl.snowdog.example.train", using: DispatchQueue.global() ) { task in self.handleMLTrain(task) } return true } private func scheduleMLTrain() { do { let request = BGProcessingTaskRequest(identifier: "pl.snowdog.example.train") request.requiresExternalPower = true request.requiresNetworkConnectivity = true try BGTaskScheduler.shared.submit(request) } catch { print(error) } } }
      
      





Important points:





Debugging



Here, too, is not without amenities. The delay between the scheduled execution time of the background task and the moment when the system starts the application to complete it can be several hours. When developing an application, you can use two private functions to launch a task and force its early completion in accordance with the selected timeline. Debugging features only work on devices.





Finally



BackgroundTasks is a great way to plan your hard work with the best user experience using your environment. Given that since the 13th version of the system, many methods for working in the background are becoming obsolete, the framework will still be very popular in applications. Given the above possibilities, this is quite logical.



I also recommend watching a video from WWDC , the examples described there are very interesting.



All Articles