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

151 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
3.6k
Jun ’22
Background Modes for Audio Playback
Summary: I'm developing an iOS audio app in Flutter that requires background audio playback for long-form content. Despite having a paid Apple Developer Program account, the "Background Modes" capability does not appear as an option when creating or editing App IDs in the Developer Portal, preventing me from enabling the required com.apple.developer.background-modes entitlement. Technical Details: In the app that I am developing, users expect uninterrupted playback when app is backgrounded or device is locked similar to Audible, Spotify, or other audio apps that continue playing in background The Problem: When building for device testing or App Store submission, Xcode shows: Provisioning profile "iOS Team Provisioning Profile: com.xxxxx-vxxx" doesn't include the com.apple.developer.background-modes entitlement. However, the "Background Modes" capability is completely missing from the Developer Portal when creating or editing any App ID. I cannot enable it because the option simply doesn't exist in the capabilities list. What I've Tried: Multiple browsers/devices: Safari, Chrome, Firefox, incognito mode, different computers Account verification: Confirmed paid Individual Developer Program membership is active New App IDs: Created multiple new App IDs - capability never appears for any of them Documentation review: Followed all Apple documentation for configuring background execution modes Different regions: Tried changing portal language to English (US) Cache clearing: Logged out, cleared cookies, tried different sessions Apple Support Response: Contacted Developer Support (Case #102633509713). Received generic documentation links and was directed to Developer Forums rather than technical escalation. Has anyone else experienced the "Background Modes" capability missing from their Developer Portal? Has anyone successfully used the App Store Connect API to add background-modes when the GUI doesn't show it? What's the proper escalation path when Developer Support provides generic responses instead of technical assistance? Things I have attempted to solve this: audio_service package: Implemented as potential workaround, but still requires the system-level entitlement Manual provisioning profiles: Cannot create profiles with required entitlement if capability isn't enabled on App ID Other perhaps important facts about the environment where I am building the app: macOS Sonoma Xcode 15.x Flutter 3.5.4+ Apple Developer Program (Individual, paid)
0
0
53
1d
Background or Foreground
Hi Team! Has anyone found a reliable way to detect CarPlay connection without the app needing to be in the foreground? I’m exploring a concept where, for example, as someone nears home while driving, a prompt appears on the CarPlay screen asking “Would you like to turn on the lights / open garage?” triggered by proximity and CarPlay connection. Would be cool to have it work automatically, but knowing you're in the car is kind of important. From what I can see, apps can’t reliably detect CarPlay connection unless they’re actively open on the CarPlay screen. Most background detection methods (like external screen connect notifications) appear deprecated. That is, unless you're specifically approved as a "messaging" or "navigation" app that appear to get special privilages to send alerts from the background. If I send an alert (or poll Carplay periodically) it just gives silent/dead response. Is there any approach, framework, entitlement, or UI pattern that could allow a passive trigger or background detection while driving with CarPlay connected? I can't see any way to bring an app to the foreground either. Not looking to abuse any rules... just want to understand if anyone’s found a clean, approved workaround. Thanks in advance!
0
0
42
2w
Maximise background update on WatchOS
I'm looking to maximise my Watch app's widget to be as up to date as possible. If we imagined the app was a simple step counter, and we wanted to display the users count as up to date as possible. We can conclude: We don't care about widget timelines beyond the current entry as we can't predict the future! We need to refresh the count as often as possible The refresh should be very quick with a straightforward HealthKit query, no networking or heavy work needed. We will assume the user has the complication/widget on their active Watch face. With the standard WidgetKit APIs we can expire the timeline after 15 minutes and in my experimentation a Watch app can usually update its widget timeline at that frequency if it's on the Watch face. I'm experimenting with two methods to try and improve refreshes further A user's step count might not have recently changed when the timeline update is called. I was therefore looking into the HealthKit enableBackgroundDelivery API (which requires the HealthKit Background Delivery entitlement to be enabled) to get updates limited to once an hour from a HKObserverQuery, I can then call the WidgetCenter.shared.reloadAllTimelines() from there. WatchOS also support the BGAppRefreshTaskRequest(identifier:"") and .backgroundTask(.appRefresh) APIs. I can request updates once every 15 minutes here too and then call the WidgetCenter.shared.reloadAllTimelines(). With option 1, this update opportunity is great as it will specifically update when there's new steps so even once an hour this would be helpful (A real shame to be limited to once an hour even if this used up WidgetKit standard reload budgets: FB13879817, FB11677132, FB10016177). But I can't determine if this update takes away one of the standard timeline expiration updates that already run 4 times an hour? Could I observe additional Health types to get additional updates? Do I need the Background Modes Capability as well as the HealthKit Background Delivery for this in Xcode or just the HealthKit one? With option 2, I can't find a suitable option in the (short) list of supported background modes in Xcode. Does not selecting any mean my app will get 0 refreshes from this route and so should not be implemented in my use case?
3
0
70
1w
Avoiding Shortcut Intent Timeout When Uploading or Downloading Large Files
Hey everyone, I have an issue I'm running into – maybe someone has the expertise to help! I've created an app that adds Intents to the Shortcuts app, to interact with S3-compatible object storage. Everything works fine, until you decide to upload/download a large file, that your internet connection cannot handle in the ~30-second intent timeout. I've explored uploading files with a background task which seems to work somehow, but the bigger issue would be downloading larger files, as other parts of the subsequent shortcut may rely on it. To the question: Is there some way of increasing the timeout for a shortcuts intent, or a way to "trick" shortcuts into letting my custom intents download/upload files without timing out? Thanks so much!
0
0
49
2w
XCFramework Location Behavior Differs from Standalone App in Background/Sleep Mode
Hi Apple Dev Team & Community, We’ve encountered an issue with background location updates when using an XCFramework we’ve built from our main app. Context: We have a standalone app called TravelSafely that reliably performs background location updates and alerts, even during sleep mode. From this app, we extracted some core functionality into an XCFramework, including location management, and provided it as an SDK to a client. We created a demo app to test this SDK in isolation. Problem: In the demo app, we notice that location updates work fine in the foreground. However, in the background or sleep mode, location updates sometimes stop completely. When we bring the app to the foreground again, location resumes. This does not happen in the original standalone app. What We’ve Already Checked: UIBackgroundModes includes location Info.plist has the required permissions Location is started correctly using startUpdatingLocation We maintain strong references and use background tasks as needed Question: Why would an app using a binary XCFramework (with location logic) behave differently from the original app in terms of background execution? Is there any known issue or recommendation when working with SDKs/XCFrameworks that need to manage background tasks and location updates? Any insights or recommendations to maintain proper background behavior would be highly appreciated. Thank you!
10
0
73
2w
Real-time audio application on locked device
I would like to inquire about the feasibility of developing an iOS application with the following requirements: The app must support real-time audio communication based on UDP. It needs to maintain a TCP signaling connection, even when the device is locked. The app will run only on selected devices within a controlled (closed) environment, such as company-managed iPads or iPhones. Could you please clarify the following: Is it technically possible to maintain an active TCP connection when the device is locked? What are the current iOS restrictions or limitations for background execution, particularly related to networking and audio? Are there any recommended APIs or frameworks (such as VoIP, PushKit, or Background Modes) suitable for this type of application?
1
0
70
Jun ’25
Location streaming onto Live Activity
Hello forum, I want to keep my app running in the background after user swaps up, for the purpose of workout tracking. start up the task and continuously receipt GPS updates process the location data show the data on a live activity Two examples Strava paddlelogger Question: Does this mean, these two apps would just pause when the .backgroundTimeRemaining becomes 0? How does a workout app "work" in background mode, do I need to handle budget running out?
2
0
44
Jun ’25
Background App Refresh
Hi, I have a couple questions about background app refresh. First, is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background? Second, despite importing BackgroundTasks, I am getting the error "cannot find operationQueue in scope". What can I do to resolve that? Thank you. func scheduleAppRefresh() { let request = BGAppRefreshTaskRequest(identifier: "peaceofmindmentalhealth.RoutineRefresh") // Fetch no earlier than 15 minutes from now. request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) do { try BGTaskScheduler.shared.submit(request) } catch { print("Could not schedule app refresh: \(error)") } } func handleAppRefresh(task: BGAppRefreshTask) { // Schedule a new refresh task. scheduleAppRefresh() // Create an operation that performs the main part of the background task. let operation = RefreshAppContentsOperation() // Provide the background task with an expiration handler that cancels the operation. task.expirationHandler = { operation.cancel() } // Inform the system that the background task is complete // when the operation completes. operation.completionBlock = { task.setTaskCompleted(success: !operation.isCancelled) } // Start the operation. operationQueue.addOperation(operation) } func RefreshAppContentsOperation() -> Operation { }
14
0
147
3d
Audio and VoIP background mode
I am building banking application which has audio/video and text chat. It is intended for contacting bank support. When user device has auto lock on after 30 seconds, session is ended, and user needs to initiate it again. Will Apple allow this kind of application to have Audio, Airplay, and Picture in Picture or Voice over IP for background modes for this kind of application or it is against Apple rules (per 2.5.4 - https://developer.apple.com/app-store/review/guidelines/)? Chat framework uses Web sockets and SIP.
1
0
75
May ’25
How to prevent the main app from being terminated by the system during long - term system - level recording
After logging in to the main App, turn on screen recording, then switch to the interface of another App to perform operations. After about ten-odd minutes, when returning to the main App, it was found that the app was forcefully quit by the system, and subsequent operations could not be carried out.
1
0
40
May ’25
SwiftData + CloudKit causes watchOS app termination during WKExtendedRuntimeSession (FB17685611)
Hi all, I’m encountering a consistent issue with SwiftData on watchOS when using CloudKit sync. After enabling: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .automatic) …the app terminates ~30–60 seconds into a WKExtendedRuntimeSession. This happens specifically when: Always-On Display is OFF The iPhone is disconnected or in Airplane Mode The app is running in a WKExtendedRuntimeSession (e.g., used for meditation tracking) The Xcode logs show a warning: Background Task ("CoreData: CloudKit Setup"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. It appears CloudKit sync setup is being triggered automatically and flagged by the system as an unmanaged long-running task, leading to termination. Workaround: Switching to: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .none) …prevents the issue entirely — no background task warning, no crash. Feedback ID submitted: FB17685611 Just wanted to check if others have seen this behavior or found alternative solutions. It seems like something Apple may need to address in SwiftData’s CloudKit handling on watchOS.
1
1
104
May ’25
Best Practices for Logging and Error Reporting in macOS Daemon Applications
Hi all, I'm working on a non-interactive macOS application (a service or daemon), and I'm trying to understand the best practices around logging and error reporting, particularly in failure scenarios. If a daemon or service fails in macOS, where is it expected to log errors, and how can users or developers discover what went wrong? Specifically, I have a few questions: What is the recommended location or system for logging errors from a non-interactive macOS application? Should we use os_log, standard error output, or write directly to files somewhere? How can a user or developer access these logs to diagnose issues—should logs be visible via the Console app? Is there a standard approach to making failure information easily accessible for debugging and support, especially for daemons running under launchd? Any guidance or best practices would be appreciated.
1
0
73
May ’25
URLSession download looping indefinitely until it times out
Hi, I’m trying to download a remote file in the background, but I keep getting a strange behaviour where URLSession download my file indefinitely during a few minutes, without calling urlSession(_:downloadTask:didFinishDownloadingTo:) until the download eventually times out. To find out that it’s looping, I’ve observed the total bytes written on disk by implementing urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:). Note that I can't know the size of the file. The server is not able to calculate the size. Below is my implementation. I create an instance of URLSession like this: private lazy var session: URLSession = { let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) configuration.isDiscretionary = false configuration.sessionSendsLaunchEvents = true return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) }() My service is using async/await so I have implemented an AsyncThrowingStream : private var downloadTask: URLSessionDownloadTask? private var continuation: AsyncThrowingStream<(URL, URLResponse), Error>.Continuation? private var stream: AsyncThrowingStream<(URL, URLResponse), Error> { AsyncThrowingStream<(URL, URLResponse), Error> { continuation in self.continuation = continuation self.continuation?.onTermination = { @Sendable [weak self] data in self?.downloadTask?.cancel() } downloadTask?.resume() } } Then to start the download, I do : private func download(with request: URLRequest) async throws -> (URL, URLResponse) { do { downloadTask = session.downloadTask(with: request) for try await (url, response) in stream { return (url, response) } throw NetworkingError.couldNotBuildRequest } catch { throw error } } Then in the delegate : public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let response = downloadTask.response, downloadTask.error == nil, (response as? HTTPURLResponse)?.statusCode == 200 else { continuation?.finish(throwing: downloadTask.error) return } do { let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let savedURL = documentsURL.appendingPathComponent(location.lastPathComponent) try FileManager.default.moveItem(at: location, to: savedURL) continuation?.yield((savedURL, response)) continuation?.finish() } catch { continuation?.finish(throwing: error) } } I also tried to replace let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) by let configuration = URLSessionConfiguration.default and this time I get a different error at the end of the download: Task <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1> failed strict content length check - expected: 0, received: 530692, received (uncompressed): 0 Task <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https:/<host>:8190/proxy?Func=downloadVideoByUrl&SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, NSErrorFailingURLKey=https://<host>:8190/proxy?Func=downloadVideoByUrl&SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDownloadTask <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1>, NSUnderlyingError=0x300d9a7c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x302139db0 [0x1fcb1f598]>{length = 16, capacity = 16, bytes = 0x10021ffe91e227500000000000000000}}}} The log "failed strict content length check” made me look into the response header, which has the following: content-length: 0 Content-Type: application/force-download Transfer-encoding: chunked Connection: KEEP-ALIVE Content-Transfer-Encoding: binary So it should be fine the way I setup my URLSession. The download works fine in Chrome/Safari/Chrome or Postman. My code used to work a couple of weeks before, so I expect something has changed on the server side, but I can’t find what, and I don’t get much help from the guys on the server side. Has anyone an idea of what’s going on?
1
0
72
May ’25
Background process not working in TestFlight
Hi everyone, I recently built an iOS application that fetches the healthkit data with the BGProcessingTask. It is working as expected in the debug with the physical device connected but its not working in Testflight. I printed out the logs but they don't show that the background process's running. Here is my code snippet. func registerBackgroundTask() { BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { task in LogManager.shared.addBackgroundProcessLog("registering the background task...") print("registering the background task...") self.handleBackgroundTask(task: task as! BGProcessingTask) } } func scheduleBackgroundHealthKitSync() { print("scheduling background task...") LogManager.shared.addBackgroundProcessLog("scheduling background task...") let request = BGProcessingTaskRequest(identifier: taskIdentifier) request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 1) request.requiresNetworkConnectivity = true request.requiresExternalPower = false do { try BGTaskScheduler.shared.submit(request) print("BGProcessingTask scheduled") LogManager.shared.addBackgroundProcessLog("BGProcessingTask scheduled") } catch { print("Failed to schedule task: \(error)") LogManager.shared.addBackgroundProcessLog("Failed to schedule task: \(error)", isError: true) print(LogManager.shared.backgroundProcessLogs) } } func handleBackgroundTask(task: BGProcessingTask) { LogManager.shared.addBackgroundProcessLog("handleBackgroundTask triggered") print("handleBackgroundTask triggered") let dispatchGroup = DispatchGroup() dispatchGroup.enter() // Reschedule the background sync for the next time scheduleBackgroundHealthKitSync() var taskCancelled = false // Handling expiration task.expirationHandler = { taskCancelled = true LogManager.shared.addBackgroundProcessLog("Background task expired", isError: true) print("Background task expired") dispatchGroup.leave() } let healthKitManager = HealthKitManager.shared // Start the background sync operation healthKitManager.fetchAndSendAllTypes() { success in if success { LogManager.shared.addBackgroundProcessLog("HealthKit sync completed successfully") print("HealthKit sync completed successfully") } else { LogManager.shared.addBackgroundProcessLog("HealthKit sync failed", isError: true) print("HealthKit sync failed") } dispatchGroup.leave() } // Notify when all tasks are completed dispatchGroup.notify(queue: .main) { // Check if the task was cancelled using your own flag or state if taskCancelled { task.setTaskCompleted(success: false) // Fail the task if it was cancelled } else { task.setTaskCompleted(success: true) // Complete successfully if not cancelled } LogManager.shared.addBackgroundProcessLog("Background task ended with status: \(taskCancelled == false)") print("Background task completed with success: \(taskCancelled == false)") // Logs success or failure } } Here are the logs from my device. scheduling background task... BGProcessingTask scheduled
1
0
63
May ’25
Xcode failed to provision target. File a bug report...
I do have background Modes added to Xcode. How can I fix this? Automatic signing failed Xcode failed to provision this target. Please file a bug report at https://feedbackassistant.apple.com and include the Update Signing report from the Report navigator. Provisioning profile "iOS Team Provisioning Profile: com.designoverhaul.bladerunner" doesn't include the com.apple.developer.background-modes entitlement. I emailed Dev Support but they said they cant help. Thank you.
4
0
152
May ’25
BGAppRefreshTask Canceled Immediately by dasd in Network Extension
Dear Apple Support Team, My app, io.cylonix.sase, has a BGAppRefreshTask (io.cylonix.sase.ios.refresh) that is canceled by dasd ~9ms after submission from a Network Extension. Please help identify the cause and suggest a solution. App Details: App ID: io.cylonix.sase iOS Version: 17.1.1 (iPhone Xs Max) Network Extension: saseWgNetworkExtension with packet-tunnel-provider entitlement Use Case: VPN app; Network Extension records file receipts in shared group UserDefaults and schedules BGAppRefreshTask to wake the main app. App Usage: High (frequently used) System State: Sufficient resources (not low on battery or memory) Issue: The task is submitted but canceled immediately with priority 10. It has never run, so rate-limiting is not an issue. ` debug 22:09:37.952749-0700 dasd Best binding found for evaluator 0x16d541720: <private> debug 22:09:37.954483-0700 dasd Invoking selector backgroundTaskSchedulerPermittedIdentifiersWithContext:tableID:unitID:unitBytes: on <LSApplicationRecord 0x724844650> default 22:09:37.955563-0700 dasd CANCELED: bgRefresh-io.cylonix.sase.ios.refresh:ABDAFA at priority 10 <private>!
6
0
79
May ’25
Prevent my app from background activity
When I search, it's always people trying to do stuff in the background. I want my app to only do stuff when it is active. And this post https://developer.apple.com/forums/thread/685525 seems to have prevented replies from the start. Which means it's just a documentation page and does not belong in the discussion forums at all, because it prevents all discussion.
1
0
46
May ’25
no option for "Extended Runtime Session"
How can I enable "Extended Runtime Sessions" for a companion watch app? Here https://developer.apple.com/documentation/watchkit/using-extended-runtime-sessions in targets under 'Signing & Capabilities' I checked "Audio" and Session Type 'Mindfulness', I created an ExtendedRuntimeManager.swift file. When running a simulation the error message says "Extended Runtime Session ungültig: Reason=-1, Error=This application does not have appropriate permissions to schedule a session." How does the app get the 'appropriate permissions'?
1
0
73
May ’25