<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dominik Babić on Medium]]></title>
        <description><![CDATA[Stories by Dominik Babić on Medium]]></description>
        <link>https://medium.com/@dbabic_38867?source=rss-4df354187e49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*A5AdiJwnEqRRtr1Q</url>
            <title>Stories by Dominik Babić on Medium</title>
            <link>https://medium.com/@dbabic_38867?source=rss-4df354187e49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:14:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dbabic_38867/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Background Tasks on iOS]]></title>
            <link>https://medium.com/@dbabic_38867/background-tasks-on-ios-c27366723b6d?source=rss-4df354187e49------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27366723b6d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[background-task]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Dominik Babić]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 07:41:56 GMT</pubDate>
            <atom:updated>2024-06-07T07:41:56.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3VjH69N06j32rLYE" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Managing tasks that need to run in the background has always been a challenge. With the introduction of <em>BackgroundTasks</em> framework in 2019, Apple has provided a tool that lets us handle this in a more efficient manner.</p><p>This framework allows you to run code in the background without having to worry about affecting user’s experience or impacting app performance.</p><p>In this article, we’ll explore how <em>BackgroundTasks</em> framework works, its key features, and provide examples on how to integrate it into your iOS projects.</p><h3>Types of background tasks</h3><p><em>BackgroundTasks</em> framework currently supports three types of tasks, each with its own use case:</p><ol><li>Background App Refresh Task (<a href="https://developer.apple.com/documentation/backgroundtasks/bgapprefreshtask"><em>BGAppRefreshTask</em></a>):</li></ol><ul><li>Ideal for short-running operations such as refreshing information or syncing small bits of data.</li><li><a href="https://developer.apple.com/videos/play/wwdc2019/707?time=1128">Limited to 30 seconds</a>.</li></ul><p>2. Background Processing Task (<a href="https://developer.apple.com/documentation/backgroundtasks/bgprocessingtask"><em>BGProcessingTask</em></a>):</p><ul><li>Ideal for long-running operations that require significant resources such as maintenance, data processing, or handling large uploads/downloads.</li><li>Can run for several minutes, but system can choose to interrupt the task.</li><li>Runs when the device is idle. System terminates the task when user starts using the device.</li></ul><p>3. Background Health Research Task (<a href="https://developer.apple.com/documentation/backgroundtasks/bghealthresearchtask"><em>BGHealthResearchTask</em></a>):</p><ul><li>Similar to <em>Background Processing Task.</em></li><li>Used to prepare data for health research studies.</li></ul><p>Tasks above have an associated <em>Background Modes</em> capability which your app must have enabled in order to allow use of a given task type. So lets see how we can enable these modes.</p><h3>Background Modes capability</h3><p>Normally, when user backgrounds the app, it ends up in a suspended state. This state imposes certain restrictions, preventing the app from running the code that it would normally run in an active state.</p><p>However, there are certain <a href="https://developer.apple.com/documentation/xcode/configuring-background-execution-modes">background modes</a> which can be used to run the code while the app is in the background. <em>BackgroundTasks</em> framework relies on two such modes — Background fetch and Background processing— former being used for <em>BGAppRefreshTask</em>, latter being used for <em>BGProcessingTask</em> and <em>BGHealthResearchTask</em>.</p><p>To add <em>Background Modes</em> capability to your project you need to do the following:</p><ul><li>In <em>Project navigator</em> select your project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*uPKkKX3Y8JcGocQMM5_Q_g.png" /><figcaption>Selecting a project from Project navigator</figcaption></figure><ul><li>Under <em>Targets</em>, select your desired target.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*VyYvTMAsf8PVtS82iwb3NA.png" /><figcaption>Selecting a target from Targets section</figcaption></figure><ul><li>Next, click on <em>Signing &amp; Capabilities </em>in tab bar.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_LtPTLVZFEOC0EM5Lxh5Q.png" /><figcaption>Selecting Signing &amp; Capabilities in tab bar</figcaption></figure><ul><li>Once selected, click on <em>+ Capability</em> to add a new capability to the target.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*ICbPWMqTYo_LqJMG12Yojw.png" /><figcaption>Adding new Capability</figcaption></figure><ul><li>From shown popup, double-click on <em>Background Modes</em> to add it as a<em> Capability</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yy_keu-2MLcUA0l4U_WkgA.png" /><figcaption>Selecting new Capability — Background Modes.</figcaption></figure><ul><li>You will notice a new section added to the <em>Signing &amp; Capabilities</em> called <em>Background Modes</em>. Depending on your use case, you may need to enable Background fetch and/or Background processing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*Wj4O6FPfto2hfxHHHlAUCg.png" /><figcaption>Enabling Background Modes for BackgroundTasks framework.</figcaption></figure><p>By enabling these Background Modes, your app will be allowed to register, schedule, and perform background tasks. Before we get to all that, there is one more step that we need to take — we need to provide a list of task identifiers that are permitted to be used by your app.</p><h3>Permitted task identifiers</h3><p>For each task that you wish to run in the background, you must register a unique task identifier with your project’s property list. By doing so, system will be able to recognize these tasks and manage them appropriately. Moreover, if you are handling multiple different tasks, having a unique identifier allows you to differentiate between them, and handle them according to their purpose.</p><p>To register these task identifiers, you will need to edit your <em>Info.plist</em> file and add a new item to the list — <em>Permitted background task scheduler identifiers</em> corresponding to <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/bgtaskschedulerpermittedidentifiers">BGTaskSchedulerPermittedIdentifiers</a> key. Once added, your property list should contain something similar to this:</p><pre>&lt;key&gt;BGTaskSchedulerPermittedIdentifiers&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;string&gt;com.dbabic.BackgroundTasksExample&lt;/string&gt;<br>&lt;/array&gt;</pre><p>It is recommended to use reverse domain notation, but theString value can be anything as long as it is unique.</p><p>There is one thing of note here, official documentation states the following:</p><blockquote>In iOS 13 and later, adding a <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/bgtaskschedulerpermittedidentifiers">BGTaskSchedulerPermittedIdentifiers</a> key to the Info.plist disables the <a href="https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623125-application">application(_:performFetchWithCompletionHandler:)</a> and <a href="https://developer.apple.com/documentation/uikit/uiapplication/1623100-setminimumbackgroundfetchinterva">setMinimumBackgroundFetchInterval(_:)</a> methods.</blockquote><p>With the above step completed, it is now possible to register and schedule background tasks.</p><h3>Registering tasks</h3><p>Now that all the prerequisites have been met, we can get into the actual code.</p><p>The entire process starts with the app launch sequence. In order to schedule tasks, you must first register their unique identifiers before the end of the app launch sequence. For this you will need to modify application(_:,didFinishLaunchingWithOptions:) method of your <em>AppDelegate</em>.</p><p>Your code should look something like this:</p><pre>// 1. Import framework<br>import BackgroundTasks<br><br>class AppDelegate: NSObject, UIApplicationDelegate {<br>  func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions<br>    launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil<br>  ) -&gt; Bool {<br>    // 2. Register task identifier with BGTaskScheduler<br>    BGTaskScheduler.shared.register(<br>      forTaskWithIdentifier: &quot;com.dbabic.BackgroundTasksExample&quot;,<br>      using: nil<br>    ) { [weak self] task in<br>      // 3. Implement launch handler<br>      self?.handleBackgroundTask(task)<br>    }<br>        <br>    return true<br>  }<br>}</pre><ol><li>We start by importing <em>BackgroundTasks</em> framework, which is the one that we will be using for all our task related operations.</li><li>Register a task identifier with the <em>BGTaskScheduler</em>. You can provide a custom DispatchQueue for using parameter. If you use nil, it will use the default background queue.</li><li>Provide a launch handler that will be called when the task is invoked.</li></ol><p>Pretty straightforward, right? Well yes, but there are some things that we must keep in mind here.</p><p>register(forTaskWithIdentifier:using:) method returns true when task identifier has been scheduled successfully. It will return false if the identifier is not included in the <em>Permitted background task identifiers</em> Info.plist.</p><p>Additionally, official documentation states the following:</p><blockquote>Register each task identifier only once. The system kills the app on the second registration of the same task identifier.</blockquote><p>The above statement is the reason why we must use unique task identifiers.</p><h3>Scheduling tasks</h3><p>Once registered, we can schedule our tasks. This can be done anywhere in the code. If you wish to schedule tasks only when the app is backgrounded, then it is best to use applicationDidEnterBackground(_:) method of your <em>AppDelegate</em>.</p><pre>func applicationDidEnterBackground(<br>  _ application: UIApplication<br>) {<br>  scheduleBackgroundTask()<br>}<br><br>func scheduleBackgroundTask() {<br>  // 1. Start by creating a new BGTaskRequest.<br>  // For BGAppRefreshTask<br>  let appRefreshTaskRequest = BGAppRefreshTaskRequest(<br>    identifier: &quot;com.dbabic.BackgroundTasksExample&quot;<br>  )<br><br>  // For BGProcessingTask<br>  let processingTaskRequest = BGProcessingTaskRequest(<br>    identifier: &quot;com.dbabic.BackgroundTasksExample&quot;<br>  )<br><br>  // For BGHealthResearchTask<br>  let healthResearchTaskRequest = BGHealthResearchTaskRequest(<br>    identifier: &quot;com.dbabic.BackgroundTasksExample&quot;<br>  )<br>        <br>  ...   <br>}</pre><p>We start by building a BGTaskRequest (step 1.). Depending on your use case, you will need to use an appropriate task request type.</p><p>It is important to note that each request type exposes properties that can be configured based on your needs.</p><p>All types expose earliestBeginDate property which allows you to define the Date when you would like the system to invoke the task. It does not guarantee that the task will be invoked at exactly that moment, it simply instructs the system <a href="https://developer.apple.com/videos/play/wwdc2019/707/?time=1746">not to invoke the task earlier</a> than set Date.</p><p>BGProcessingTaskRequest exposes two additional properties that can be set:</p><pre>...<br>processingTaskRequest.requiresExternalPower = true | false<br>processingTaskRequest.requiresNetworkConnectivity = true | false</pre><p>These properties provide additional constraints for your request. If you set requiresExternalPower to true, this will inform the system to invoke the task only when the device is connected to a charger. Additionally, <a href="https://developer.apple.com/videos/play/wwdc2019/707/?time=1987">it disables CPU monitoring</a>, allowing your app to use resources without having to worry it will be terminated by the system.</p><p>Similarly, if you set requiresNetworkConnectivity to true, it will inform the system that the task requires active network connection in order to run.</p><p>BGHealthResearchTaskRequest exposes protectionTypeOfRequiredData property which determines the file protection level.</p><p>Once we have our BGTaskRequest, we can go ahead and submit it to the scheduler.</p><pre>func scheduleBackgroundTask() {      <br>  ...<br><br>  do {<br>    // 2. Submit the request<br>    try BGTaskScheduler.shared.submit(appRefreshTaskRequest)<br>  } catch {<br>    // 3. (Optional) Handle thrown errors<br>    print(error.localizedDescription<br>  }   <br>}</pre><p>When we call submit(_:) method of BGTaskScheduler, we tell the system that we want to schedule a task based on the request provided. There are a few possible error that can be thrown our way here. For more information see <a href="https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler/error/code">BGTaskScheduler.Error.Code</a>.</p><p>There are a few things that we must keep in mind when submitting task requests to BGTaskScheduler. Per <a href="https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler/submit(_:)">official documentation</a>:</p><blockquote>Submitting a task request for an unexecuted task that’s already in the queue replaces the previous task request.</blockquote><blockquote>There can be a total of 1 refresh task and 10 processing tasks scheduled at any time. Trying to schedule more tasks returns <a href="https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler/error/code/toomanypendingtaskrequests">BGTaskScheduler.Error.Code.tooManyPendingTaskRequests</a>.</blockquote><h3>Task launch handler</h3><p>Now that the request has been submitted, we can implement the logic that will handle our background tasks.</p><pre>func handleBackgroundTask(<br>  _ task: BGTask<br>) {<br>  // 1. Reschedule the task<br>  scheduleBackgroundTask()<br>        <br>  // 2. Provide expiration handler<br>  task.expirationHandler = {<br>            <br>    // 4.2.<br>    task.setTaskCompleted(success: false)<br>  }<br>        <br>  // 3. Perform neccesary work<br>  Task { [weak self] in<br>    guard let self else {<br>      // 4.2.<br>      task.setTaskCompleted(success: false)<br>      return<br>    }<br>            <br>    do {<br>      let data = try await self.performNetworkRequest()<br>                <br>      // 4.1.<br>      task.setTaskCompleted(success: true)<br>    } catch {<br>      // 4.2.<br>      task.setTaskCompleted(success: false)<br>    }<br>  }<br>}</pre><p>When your registered a task, you provided a launch handler that calls handleBackgroundTask(_:) method when task is invoked by the system.</p><p>In the example above the method does the following:</p><ol><li>Immediately reschedules another task. This allows the system to continuously invoke tasks to be performed in the background. Tasks can be scheduled with specific time interval in mind, based on your requirements.</li><li>Sets task’s expirationHandler. Seeing how the task can expire or get interrupted by the system, it is highly advised to provide an expirationHandler.</li><li>Performs any necessary work for which the task was scheduled. This can be anything from simple network requests to complex data processing.</li><li>Once task is finished — either by completing the work or expiring — it is necessary to inform the system that the task is done. <a href="https://developer.apple.com/documentation/backgroundtasks/bgtask/settaskcompleted(success:)#:~:text=Not%20calling%20setTaskCompleted(success%3A)%20before%20the%20time%20for%20the%20task%20expires%20may%20result%20in%20the%20system%20killing%20your%20app.">Failing to do so will cause the system to terminate the app</a>.</li></ol><ul><li>In the case of task completing successfully , call setTaskCompleted(success: true).</li><li>In the case of task failing or expiring before it completes the work, call setTaskCompleted(success: false).</li></ul><p>With this method, <em>BackgroundTasks</em> integration is complete.</p><h3>Testing integration</h3><p>As previously stated, the system is responsible for invoking scheduled tasks. It chooses when the task will be invoked based on the device conditions such as battery level, network connection, and others. This makes testing <em>BackgroundTasks</em> integration difficult as we cannot predict when the task will actually be invoked. We might schedule a task for 5 minutes into the future, but there is no guarantee that the system will invoke the task at that moment.</p><p>To get around these limitations, Apple has <a href="https://developer.apple.com/documentation/backgroundtasks/starting-and-terminating-tasks-during-development">provided a way</a> to invoke the task through the debugger. To start, you will need <a href="https://developer.apple.com/documentation/backgroundtasks/starting-and-terminating-tasks-during-development#:~:text=The%20debug%20functions%20work%20only%20on%20devices">a physical device</a>:</p><ol><li>Install the app on your device.</li><li>When the app launches, background it in order to schedule a task.</li><li>Pause the app execution to bring up the debugger, enter the command below. Replace <em>TASK_IDENTIFIER</em> with your task ID.</li><li>Resume the app execution, system will invoke the task.</li></ol><pre>e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@&quot;TASK_IDENTIFIER&quot;]</pre><p>Similarly, if we wish to test task expiration, we can do the following:</p><ol><li>Set a breakpoint after expirationHandler has been assigned.</li><li>Invoke the task by running the command above.</li><li>Wait for the breakpoint to trigger.</li><li>In the debugger, run the command below, once again replacing TASK_IDENTIFIER with your task ID.</li><li>Resume the app execution, expirationHandler will be invoked.</li></ol><pre>e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@&quot;TASK_IDENTIFIER&quot;]</pre><p>Even though testing using these methods does not match the real life scenario and the behavior of the system, it is sufficient enough to allow us to test our integration and confirm that the tasks perform the operations that we want to do.</p><h3>Final thoughts</h3><p>While the integration process is fairly simple, there are plenty of things that must be considered when working with <em>BackgroundTasks</em> framework.</p><p>One of the common misconceptions when working with the framework is that setting the task begin date is guaranteed to cause the system to invoke the task at the given time. Going through my logs, I have noticed that this time can vary depending on a lot of different factors. Perhaps your battery level is not sufficient for performing the task, maybe your task relies on network connection but your device is not connected, maybe your device is using a lot of system resources for some other operations, maybe other apps are also scheduling tasks. There is really no way to predict when your task will be invoked. System will attempt to do it as close to the date provided, but you cannot assume that it will happen at exactly the moment you expect it.</p><p>With the limited number of tasks that can be registered, you might need to reconsider your priorities. You can only register one BGAppRefreshTask, and if you have a lot requests that need to complete in order to refresh your app state, perhaps you will run out of time to complete the task. You might need to focus on a few requests and move the rest to processing tasks.</p><p>Processing tasks get a longer execution time, but they certainly won’t run quite as often as your refresh tasks. You must keep this in mind when assigning work to each task.</p><p>There is plenty of other things to consider, but the article is already long enough.</p><p>I hope this gives you some insight into how <em>BackgroundTasks</em> framework works and behaves. I have tried to cover all the important bits, in as much detail as possible. Hopefully, I have succeeded.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27366723b6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>