Background Tasks

RSS for tag

Request the system to launch your app in the background to run tasks using Background Tasks.

Posts under Background Tasks tag

129 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Background Tasks Resources
General: DevForums tag: Background Tasks Background Tasks framework documentation UIApplication background tasks documentation ProcessInfo expiring activity documentation watchOS background execution documentation WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it! WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI iOS Background Execution Limits DevForums post UIApplication Background Task Notes DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.9k
Jun ’22
Which thread to call uploadTask from URLSession
Hi, I would like to know if it is safe to call the uploadTask from URLSession from the main thread ? We've a user who is reporting repeated crashes at startup, here is the stack we see: Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.appspot.myApp(E7590BB1-722C-491D-9199-F867DE4B880A)>:2212 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Background ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 21.260 (user 10.230, system 11.030), 35% CPU", "Elapsed application CPU time (seconds): 0.006, 0% CPU" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1def7a688 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1def7dd98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1def7dcb0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x1def7dafc mach_msg + 24 4 libdispatch.dylib 0x1968d8f14 _dispatch_mach_send_and_wait_for_reply + 544 5 libdispatch.dylib 0x1968d92b4 dispatch_mach_send_with_result_and_wait_for_reply + 60 6 libxpc.dylib 0x21714a930 xpc_connection_send_message_with_reply_sync + 256 7 Foundation 0x18d80a3ac __NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__ + 16 8 Foundation 0x18d806b14 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 2160 9 CoreFoundation 0x18eb868dc ___forwarding___ + 1004 10 CoreFoundation 0x18eb86430 _CF_forwarding_prep_0 + 96 11 CFNetwork 0x1900c71e0 -[__NSURLBackgroundSession setupBackgroundSession] + 800 12 CFNetwork 0x1900b3e80 -[__NSURLBackgroundSession initWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 552 13 CFNetwork 0x1900b4784 +[NSURLSession _sessionWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 1496 14 MyApp 0x1054210b4 CombineBgXferRepository.session.getter (in MyApp) (CombineBgXferRepository.swift:62) + 7966900 15 MyApp 0x105422fa4 CombineBgXferRepository.startUploadTask(fileURL:request:) (in MyApp) (CombineBgXferRepository.swift:310) + 7974820 If it is ok to call this uploadTask from the main thread, does this crash indicate a problem with the operating system? Are there scenarios where the background upload service does not respond to requests?
3
2
114
2d
Simulate Background Fetch Not Working on Real Device, Works on Simulator
Hello Apple Support, I’m facing an issue with Background Fetch in my React Native project. When I click on Simulate Background Fetch in Xcode, everything works as expected on the iOS Simulator—background tasks run smoothly, and data is fetched without issues. However, on a real device, the app goes to the background but doesn’t execute any of the scheduled background tasks, and it also remains in the background without terminating. Here’s some additional context: React Native Project: I’m using React Native to develop this app, and the background tasks involve: Getting User Location: Fetching the user’s location in the background. API Calls: Calling an API to fetch necessary information based on the user’s location. Scheduling Notifications and Alarms: Scheduling notifications and alarms based on the API response data. Simulator vs. Real Device: In the iOS Simulator, all these background tasks trigger and function correctly when I simulate Background Fetch. On the real device, however, none of these tasks are triggered when I try to simulate Background Fetch. The app only moves to the background without performing any tasks or getting terminated. Device and Configuration Details: iOS Version: 17 Device Model: Iphone xs, Iphone 11, iphone 7 Background Modes: Background Fetch is enabled in Capabilities, and I’ve set the fetch interval to the minimum for testing. I’ve verified that all configurations are correctly set, and I’ve tried restarting the device and Xcode, but the issue persists. Is there something specific about Background Fetch that could prevent it from functioning as expected on physical devices? Any guidance on troubleshooting or additional steps would be highly appreciated. Thank you!
1
0
78
6d
What are the reasons for an application to be launched from the background?
Our application has seen a surge in the volume of background launches starting from April and May, and we want to know under what circumstances the application can be launched from the background. First, here's how I determined background launches: we analyze user logs and append UIApplication.appState to each line of log, finding that every log from the start to the end of user sessions has an appState of UIApplicationStateBackground. By checking the "ActivePrewarm" in main() and printing the launch options from application:didFinishLaunchingWithOptions:, we found several scenarios for background launches: launchOptions has a value with the key UIApplicationLaunchOptionsRemoteNotificationKey. launchOptions has no value and there is no "ActivePrewarm." launchOptions has no value but has "ActivePrewarm." I would like to know: Under what circumstances will notifications trigger a background launch (I cannot replicate this locally)? Under what circumstances does an application launch in the background and trigger application:didFinishLaunchingWithOptions: but without any launch options? I hope informations below can provide some insights. Regarding "ActivePrewarm," I've read various questions and answers in the Apple Developer Forums, such as this thread, which states that "ActivePrewarm" does not trigger application:didFinishLaunchingWithOptions: but occurs due to certain behaviors in the application. I would like to know what behaviors may cause this background launch, as there is no information in the launch options, or how I can identify what behaviors triggered it. Specifically, based on that same thread, I've tried to gather more information using runningboardd, and I've currently identified two special cases: When I restart my phone and unlock it after a short period, there is information: &lt;RBSDomainAttribute| domain:"com.apple.dasd" name:"DYLDLaunch" sourceEnvironment:"(null)"&gt; ]&gt; Every day, at intervals of a few hours, there is information: &lt;RBSDomainAttribute| domain:"com.apple.dasd" name:"DYLDLaunch" sourceEnvironment:"(null)"&gt; ]&gt; Then, the following similar information follows: 12:15:56.047625+0800 runningboardd Executing launch request for app&lt;{my_bundle_id}((null))&gt; (DAS Prewarm launch) 12:15:56.050311+0800 runningboardd Creating and launching job for: app&lt;{my_bundle_id}((null))&gt; 12:15:56.050333+0800 runningboardd _mutateContextIfNeeded called for {my_bundle_id} 12:15:56.080560+0800 runningboardd app&lt;{my_bundle_id}((null))&gt;: -[RBPersonaManager personaForIdentity:context:personaUID:personaUniqueString:] required 0.000954 ms (wallclock); resolved to {1000, 39E408CF-2E67-4DB0-BF73-CFC5792285CD} 12:15:56.080632+0800 runningboardd 'app&lt;{my_bundle_id}(39E408CF-2E67-4DB0-BF73-CFC5792285CD)&gt;' Skipping container path lookup because containerization was prevented (&lt;RBSLaunchContext: 0xcd8cc9180&gt;) 12:15:56.080939+0800 runningboardd 'app&lt;{my_bundle_id}(39E408CF-2E67-4DB0-BF73-CFC5792285CD)&gt;' Constructed job description: &lt;dictionary: 0xcd8aa2a00&gt; { count = 19, transaction: 0, voucher = 0x0, contents = *** } 12:15:56.084839+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] Memory Limits: active 4096 inactive 4096 &lt;private&gt; 12:15:56.084861+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] This process will be managed. 12:15:56.084882+0800 runningboardd Now tracking process: [app&lt;{my_bundle_id}((null))&gt;:1649] 12:15:56.084928+0800 runningboardd Calculated state for app&lt;{my_bundle_id}((null))&gt;: running-active (role: Background) (endowments: (null)) 12:15:56.086762+0800 runningboardd Using default underlying assertion for app: [app&lt;{my_bundle_id}((null))&gt;:1649] 12:15:56.086977+0800 runningboardd Acquiring assertion targeting [app&lt;{my_bundle_id}((null))&gt;:1649] from originator [app&lt;{my_bundle_id}((null))&gt;:1649] with description &lt;RBSAssertionDescriptor| "RB Underlying Assertion" ID:33-33-23101 target:1649 attributes:[ &lt;RBSDomainAttribute| domain:"com.apple.underlying" name:"defaultUnderlyingAppAssertion" sourceEnvironment:"(null)"&gt;, &lt;RBSAcquisitionCompletionAttribute| policy:AfterApplication&gt; ]&gt; 12:15:56.087203+0800 runningboardd Assertion 33-33-23101 (target:[app&lt;{my_bundle_id}((null))&gt;:1649]) will be created as active 12:15:56.087946+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] reported to RB as running 12:15:56.088053+0800 runningboardd Calculated state for app&lt;{my_bundle_id}((null))&gt;: running-active (role: Background) (endowments: (null)) 12:15:56.088114+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] Set jetsam priority to 0 [0] flag[1] 12:15:56.088136+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] Resuming task. 12:15:56.088211+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] Set darwin role to: Background 12:15:56.088449+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] set Memory Limits to Hard Inactive (4096) 12:15:56.089314+0800 runningboardd Successfully acquired underlying assertion for [app&lt;{my_bundle_id}((null))&gt;:1649] 12:15:56.589755+0800 runningboardd Invalidating assertion 33-76-23100 (target:app&lt;{my_bundle_id}((null))&gt;) from originator [osservice&lt;com.apple.dasd&gt;:76] 12:15:56.590332+0800 runningboardd Removed last relative-start-date-defining assertion for process app&lt;{my_bundle_id}((null))&gt; 12:15:56.593760+0800 runningboardd [app&lt;{my_bundle_id}((null))&gt;:1649] Suspending task. 12:15:56.594120+0800 runningboardd Calculated state for app&lt;{my_bundle_id}((null))&gt;: running-suspended (role: None) (endowments: (null)) From these logs, I understand that the system is accelerating the launch speed of the application. But the time interval between these two logs below is very short, which suggests that the prewarm is executed just before main, and then the process is suspended. Is this understanding correct? 12:15:56.089314+0800 runningboardd Successfully acquired underlying assertion ... 12:15:56.589755+0800 runningboardd Invalidating assertion ... Regarding "DAS DYLD3 Closure Generation," I speculate that after a user restarts their phone, the system uses DYLD3 to prepare closures for frequently used applications, allowing for faster application launches. Is this assumption correct?
5
0
141
3h
Background sync
I am developing an application usinh native apps, where the app needs to continuously sync data (such as daily tasks and orders) even when offline or running in the background. However, on iOS, the background sync stops after 30 seconds, limiting the functionality. The Background Sync API and Service Workers seem restricted on iOS, causing syncing to fail when the app is in the background or offline. What is the best way to ensure continuous background synchronization on iOS? Additionally, what is the most efficient data storage approach for managing offline capabilities and syncing smoothly when the network is unstable and for the background sync?
1
0
96
1w
BGProcessingTaskRequest execute randomly.
I am using BGProcessingTaskRequest to fetch a API make my app up to date. Sometimes this background task execute with 10 minutes some times it take more than 10 mins, Some other times its never execute. But in my case im provide just 1 minute to BGProcessingTaskRequest.earliestBeginDate variable. And i will share my implementation here, My codes are, Called the register function before app launching. let taskId = "_________" func registerBackgroundTaks() { BGTaskScheduler.shared.register(forTaskWithIdentifier: taskId, using: nil) { task in self.handleBackgroundProcessRequest(task: task as! BGProcessingTask) } print("Receiver called") } Called the scheduleBackgroundPrecessingTask function when application enter in background mode. func scheduleBackgroundPrecessingTask() { let request = BGProcessingTaskRequest(identifier: taskId) request.requiresNetworkConnectivity = false // Need to true if your task need to network process. Defaults to false. request.requiresExternalPower = false request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60) // Featch Image Count after 1 minute. do { try BGTaskScheduler.shared.submit(request) print("Process notification triggered") } catch { print("Could not schedule background process: \(error)") } } Could anyone share any concerns to my problem? or kindly clarify me why BGProcessingTaskRequest takes time randomly?
4
0
265
3w
POST request failing only when app goes in to background.
I'm trying to troubleshoot what is going on with my app. The app works just fine when the user is logged in. It's able to post data to my REST API just fine. But when the app goes in to the background, the BGAppRefreshTask fires off just fine, but it's unable to post its data. There payload is super small a two keys and two short strings and thats it. I've tried searching on kCFStreamErrorCodeKey -2103 and ErrorDomainKey 4 but not much comes up. Here is my error with the URL string altered... Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2103, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3126EFA1-00D3-4423-A31B-D40AB900292D>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <3126EFA1-00D3-4423-A31B-D40AB900292D>.<1>" ), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=https://my.example.com/myapi/v1/device, NSErrorFailingURLKey=https://my.example.com/myapi/v1/device, _kCFStreamErrorDomainKey=4}
2
0
122
2w
Timer driven refresh
I have an app that needs to refresh a server whenever a Contacts record is updated. I can observe Contacts, but that only seems to work when my app is running (and in foreground, which it cannot be on iPhone if the Contacts app is being updated). I want it to process, even if my app is in background, or has been terminated (swiped away), or after a phone restart. The only way I can think of is to periodically push a notification to the app from an external server. Is there any way to run a timer that sends a notification to the app on a periodic basis? The timers you can set seem to run even if the Clock app is swiped away, or following a phone restart. Is there anything like that I could use to wake my app periodically?
1
0
179
4w
Background Task in iOS App
Hi, I am working on a React Native app and i want to have a latitude longitude of a user in every 15 minutes and want to do something like an api call with it. I want to keep continuing this no matter my app is in background, foreground or in killed state. Is there any way or method through which i can achieve this natively or using React Native?
1
0
179
Oct ’24
Urgent Issue with SoundAnalysis in iOS 18 - Critical Background Permissions Error
We are experiencing a major issue with the native .version1 of the SoundAnalysis framework in iOS 18, which has led to all our user not having recordings. Our core feature relies heavily on sound analysis in the background, and it previously worked flawlessly in prior iOS versions. However, in the new iOS 18, sound analysis stops working in the background, triggering a critical warning. Details of the issue: We are using SoundAnalysis to analyze background sounds and have enabled the necessary background permissions. We are using the latest XCode A warning now appears, and sound analysis fails in the background. Below is the warning message we are encountering: Warning Message: Execution of the command buffer was aborted due to an error during execution. Insufficient Permission (to submit GPU work from background) [Espresso::handle_ex_plan] exception=Espresso exception: "Generic error": Insufficient Permission (to submit GPU work from background) (00000006:kIOGPUCommandBufferCallbackErrorBackgroundExecutionNotPermitted); code=7 status=-1 Unable to compute the prediction using a neural network model. It can be an invalid input data or broken/unsupported model (error code: -1). CoreML prediction failed with Error Domain=com.apple.CoreML Code=0 "Failed to evaluate model 0 in pipeline" UserInfo={NSLocalizedDescription=Failed to evaluate model 0 in pipeline, NSUnderlyingError=0x30330e910 {Error Domain=com.apple.CoreML Code=0 "Failed to evaluate model 1 in pipeline" UserInfo={NSLocalizedDescription=Failed to evaluate model 1 in pipeline, NSUnderlyingError=0x303307840 {Error Domain=com.apple.CoreML Code=0 "Unable to compute the prediction using a neural network model. It can be an invalid input data or broken/unsupported model (error code: -1)." UserInfo={NSLocalizedDescription=Unable to compute the prediction using a neural network model. It can be an invalid input data or broken/unsupported model (error code: -1).}}}}} We urgently need guidance or a fix for this, as our application’s main functionality is severely impacted by this background permission error. Please let us know the next steps or if this is a known issue with iOS 18.
5
9
607
3w
Ensuring Successful Video Uploads in iOS Background Mode(terminated state)
If we start uploading a video file from the foreground and then switch to another app or press the home button, we can enable background processing by selecting the 'Background processing' option in the app's background modes. We utilize URLSession to handle the upload. I have a few questions regarding this process: If the user manually kills the app, will the upload continue in the background? For files around 100 MB, if the user locks the phone while the upload is in progress (and the app is in the background but not terminated), will the upload still be successful? Does Apple provide any additional APIs that would facilitate successful file uploads even if the user terminates the app? I would appreciate any solutions or insights you can provide. Thank you!
3
0
226
Oct ’24
Background modes in Flutter project (Android Studio)
Hello, I'm developing an iOS app in Flutter, but I'm having trouble enabling Background Mode. I added the following configuration to Info.plist and Runner.entitlements: <key>UIBackgroundModes</key> <array> <string>processing</string> <string>fetch</string> <string>location</string> </array> However, the Background Mode option doesn't appear in my App ID to be enabled. And the build fails with the message: Provisioning profile "Ready Response ios_app_store ..." doesn't include the UIBackgroundModes entitlement. How can I enable this option in my App ID? Note: I'm using Android Studio and publishing through Codemagic.
2
0
431
Sep ’24
BGTask expiry is never called for the requested BGTask.
We have a push-to-talk client, Part of Push APNS, app never received the BG task expiry. The app is suspended. Received Push-To-Talk APNS Here requested a BGTask and it got successfully registered Since it is a PTT call path, it ended immediately(via code) due to internal restrictions Ex: DND mode for client specific. The client allowed BG time more than 30 seconds and looks client has been suspended but Never received a BG task expiration handler from OS In sys diagnose logs confirmed, BGTask registered successfully 2024-09-03 16:18:47.331890 +0530 default AT&T EPTT : Created background task . But never got fired expiration handler. Feedback - FB15145380
3
0
191
Oct ’24
Trouble with getting a background refresh task working
I am able to setup and schedule a background refresh task as well as manually trigger it via Xcode and the simulator tied to my iPhone 11 Pro test phone using the e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier: However, it won't execute on the app on it's own. And yes, the pinfo.list entries are correct and match! I know the scheduler is not exact on timing but it's just not executing on its own. Since I can trigger manually it I'm pretty sure the code is good but I must be missing something. I created an observable object for this code and the relevant parts look like this: class BackgroundTaskHandler: ObservableObject { static let shared = BackgroundTaskHandler() var taskState: BackgroundTaskState = .idle let backgroundAppRefreshTask = "com.opexnetworks.templateapp.shell.V1.appRefreshTask" func registerBackgroundTask() { BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundAppRefreshTask, using: nil) { task in self.handleAppRefresh(task: task as! BGAppRefreshTask) } self.updateTaskState(to: .idle, logMessage: "✅ Background app refresh task '\(backgroundAppRefreshTask)' registered.") BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in self.handleProcessingTask(task: task as! BGProcessingTask) } self.updateTaskState(to: .idle, logMessage: "✅ Background task identifier '\(backgroundTaskIdentifier)' registered.") } // Handle the app refresh task private func handleAppRefresh(task: BGAppRefreshTask) { self.updateTaskState(to: .running, logMessage: "🔥 app refresh task is now running.") PostNotification.sendNotification(title: "Task Running", body: "App refresh task is now running.") let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 let operation = BlockOperation { self.doSomeShortTaskWork() } task.expirationHandler = { self.updateTaskState(to: .expired, logMessage: "💀 App refresh task expired before completion.") PostNotification.sendNotification(title: "Task Expired", body: "App refresh task expired before completion \(self.formattedDate(Date())).") operation.cancel() } operation.completionBlock = { if !operation.isCancelled { self.taskState = .completed } task.setTaskCompleted(success: !operation.isCancelled) let completionDate = Date() UserDefaults.standard.set(completionDate, forKey: "LastBackgroundTaskCompletionDate") self.updateTaskState(to: .completed, logMessage: "🏁 App refresh task completed at \(self.formattedDate(completionDate)).") PostNotification.sendNotification(title: "Task Completed", body: "App refresh task completed at: \(completionDate)") self.scheduleAppRefresh() // Schedule the next one } queue.addOperation(operation) } func scheduleAppRefresh() { // Check for any pending task requests BGTaskScheduler.shared.getPendingTaskRequests { taskRequests in let refreshTaskIdentifier = self.backgroundAppRefreshTask let refreshTaskAlreadyScheduled = taskRequests.contains { $0.identifier == refreshTaskIdentifier } if refreshTaskAlreadyScheduled { self.updateTaskState(to: .pending, logMessage: "⚠️ App refresh task '\(refreshTaskIdentifier)' is already pending.") // Iterate over pending requests to get details for taskRequest in taskRequests where taskRequest.identifier == refreshTaskIdentifier { let earliestBeginDate: String if let date = taskRequest.earliestBeginDate { earliestBeginDate = self.formattedDate(date) } else { earliestBeginDate = "never" } self.updateTaskState(to: .pending, logMessage: "⚠️ Pending Task: \(taskRequest.identifier), Earliest Begin Date: \(earliestBeginDate)") } // Optionally, show a warning message to the user in your app PostNotification.sendNotification(title: "Pending Tasks", body: "App refresh task is already pending. Task scheduling cancelled.") return } else { // No pending app refresh task, so schedule a new one let request = BGAppRefreshTaskRequest(identifier: refreshTaskIdentifier) request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // Earliest in 15 minutes do { try BGTaskScheduler.shared.submit(request) self.taskState = .scheduled self.updateTaskState(to: .scheduled, logMessage: "✅ App refresh task '\(refreshTaskIdentifier)' successfully scheduled for about 15 minutes later.") PostNotification.sendNotification(title: "Task Scheduled", body: "App refresh task has been scheduled to run in about 15 minutes.") } catch { print("Could not schedule app refresh: \(error)") self.taskState = .failed self.updateTaskState(to: .failed, logMessage: "❌ Failed to schedule app refresh task.") } } } } // Short task work simulation private func doSomeShortTaskWork() { print("Doing some short task work...") // Simulate a short background task (e.g., fetching new data from server) sleep(5) print("Short task work completed.") } In my AppDelegate I trigger the registerBackground task in the didFinishLaunchingWithOptions here: BackgroundTaskHandler.shared.registerBackgroundTask() And I scheduled it here in the launch view under a task when visible: .task { BackgroundTaskHandler.shared.scheduleAppRefresh() } I've also tried the last in the AppDelegate after registering. either way the task schedules but never executes.
4
0
273
Sep ’24