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

137 Posts

Post

Replies

Boosts

Views

Activity

Live Activity Stops Updating After 30 Seconds in Background During Audio Playback
Hi I developed a music app that plays offline audio and displays lyrics using Live Activities. According to ActivityKit documentation, Live Activities can be updated from the background. However, in my case, updates stop after ~30 seconds when the app goes to the background or the device is locked. Important points: The app continues running in the background (audio playback works fine using AVAudioSession with .playback) Background code execution is working as expected Only the Live Activity stops updating I am not using push updates since this is an offline app. Is there any limitation or requirement for updating Live Activities continuously in the background during audio playback? Audio Session Configuration let session = AVAudioSession.sharedInstance() try session.setCategory( .playback, mode: .default, options: [.mixWithOthers] // ✅ DO NOT interrupt other audio ) try session.setActive(true) print("✅ [AudioSession] Activated with mixWithOthers") } catch { print("❌ [AudioSession] Error: \(error)") } Live Activity Update Methods guard let activity = getLiveActivity(for: recordID) else{ print("⚠️ No Live Activity found for recordID: \(recordID)") return } guard activity.activityState == .active else { print("⚠️ Activity is not active") return } Task { let content = ActivityContent( state: state, staleDate: Date().addingTimeInterval(60 * 60 * 12), relevanceScore: 1.0 ) await activity.update(content) print("✅ Live Activity updated with ActivityContent") } }
0
0
400
Apr ’26
SwiftUI View Not Initialized on Background Relaunch (CoreBluetooth / Cold Start?)
I have a question regarding cold start and pre-warming behavior on iOS. I’m developing a SwiftUI app that continuously receives data from a BLE device in the background. We’ve observed that after the BLE stream stops, the OS often terminates our app. Later, when the sensor comes back into range, iOS appears to relaunch (or reinitialize) the app. In our app, we use a WindowGroup like this: WindowGroup { AppView(store: store) } We’ve placed our BLE reconnection logic inside a .task modifier in AppView. What’s confusing is this: Most of the time, when the app is relaunched, AppView is created and the .task runs as expected. However, in about 1 out of 10 cases, AppView is not created at all, so the .task does not execute. I’m trying to understand: Under what conditions does iOS relaunch an app without fully initializing the SwiftUI view hierarchy? Is this related to pre-warming or background relaunch mechanisms (e.g., CoreBluetooth state restoration)? What determines whether the WindowGroup and root view are actually instantiated? Any insight into the system’s relaunch behavior or lifecycle in this scenario would be greatly appreciated.
2
0
227
Apr ’26
HKObserverQuery BackgroundDelivery not executed
Hi, I'm having the same issue described in https://developer.apple.com/forums/thread/690974?page=2. When connected to Xcode or when the app is in the foreground, HKObserverQuery fires correctly and my app processes step updates. But once disconnected from Xcode, background delivery stops completely and the observer callback is never called. My setup: com.apple.developer.healthkit.background-delivery entitlement is present and in the provisioning profile enableBackgroundDelivery(for: .stepCount, frequency: .immediate) returns success = true HKObserverQuery is registered on every launch including background launches I also have CMPedometer.startEventUpdates running as a supplemental trigger Background Modes includes "Background fetch" and "Background processing" Device: iPhone, iOS 17.4+ App type: App uses Screen Time / Family Controls (ManagedSettings) to block apps until a step goal is met Has anyone found a reliable fix? Any feedback from Apple engineers would be appreciated.
1
0
369
Apr ’26
Clarification on HealthKit Observer Delivery Frequency and BGTaskScheduler Behavior
Hi Team, We are implementing HealthKit data sync using HKObserverQuery along with enableBackgroundDelivery and BGTaskScheduler for fallback processing. However, we are observing inconsistent behavior and would like clarification on expected system behavior: For HKObserverQuery: When using enableBackgroundDelivery with frequency .immediate, we sometimes receive updates promptly, but other times we do not receive any trigger at all. Similarly, when using .hourly, our expectation was that updates would be delivered approximately once per hour, but in practice, triggers are delayed, batched, or skipped. For BGTaskScheduler: We are scheduling BGAppRefreshTask with earliestBeginDate set (e.g., 1 hour), but tasks are sometimes delayed by several hours or not triggered predictably. In some cases, tasks are not executed even after extended periods. We would like to understand: Are HKObserverQuery delivery frequencies (.immediate, .hourly, .daily) strictly best-effort hints rather than guaranteed intervals? Under what conditions can observer updates be skipped or significantly delayed? Is there any recommended approach to ensure more reliable periodic syncing of HealthKit data? For BGTaskScheduler, what factors most strongly influence scheduling delays or missed executions? Our goal is to design a reliable sync mechanism, but the lack of deterministic behavior is making it difficult to define expected system behavior. Any clarification or recommended best practices would be greatly appreciated. Thanks in advance!
1
0
301
Apr ’26
Receiving MPMusicPlayerController playback notifications when app is suspended
Heyy, I'm building a music tracking app that logs a user's Apple Music plays to build a personal weekly chart. The core mechanic depends on accurately counting how many times a user plays each track. My current implementation uses MPMusicPlayerController.systemMusicPlayer with beginGeneratingPlaybackNotifications() and observes MPMusicPlayerControllerNowPlayingItemDidChange. This works well when the app is in the foreground or recently backgrounded, but notifications stop firing once iOS suspends the app. To get around this I've implemented: applicationDidBecomeActive - restarts the monitor and logs the currently playing track on every foreground Background fetch (performFetchWithCompletionHandler) - periodically wakes the app to log what's playing. This gives some coverage but misses plays that happen between background fetch intervals or when the user hasn't opened the app in a while. The result is an inaccurate play count which undermines the core feature. My questions: Is there a supported entitlement or capability that would allow an app to receive MPMusicPlayerController playback notifications while suspended? Is MusicKit or MediaPlayer the recommended framework for this use case, or is there a better API I'm not aware of? Are there any supported background modes that would keep playback notification delivery alive without requiring the app to be a full audio player? I've looked at MusicRecentlyPlayedRequest but it only returns the last 25 items with no play counts, so it can't tell me a track was played 10 times vs once. Any guidance on the right approach here would be really appreciated.
2
0
232
Apr ’26
Background Assets: Downloaded .aar not working — "bundle record couldn't be looked up" error (-10814)
Platform: iOS 26 (23E254) Xcode: 26.0 Reproduces on: Debug builds AND TestFlight Summary: I'm using Apple-Hosted Managed Background Assets with on-demand download policy. The .aar archives download successfully (correct file size, status = downloaded), but the contents are never extracted into the asset pack namespace. AssetPackManager.shared.contents(at:) returns fileNotFound for all path variants, and url(for: FilePath(".")) returns a URL that exists but contains zero children. Root Cause from Sysdiagnose: The backgroundassets.user daemon logs reveal this error on every download attempt: A bundle record couldn't be looked up for the application identifier "AtlasDrift.SnapTrail": Error Domain=NSOSStatusErrorDomain Code=-10814 "(null)" UserInfo={_LSFile=LSBindingEvaluator.mm, _LSLine=1973, _LSFunction=runEvaluator} Error code -10814 is kLSApplicationNotFoundErr. The BA daemon downloads the .aar blob, then attempts to find the app bundle via LaunchServices to locate the extension for extraction — but the LS lookup fails. Without the extension, extraction never occurs. Verified Configuration Everything matches the documentation and WWDC sessions: Extension embedded at SnapTrail.app/Extensions/BackgroundDownloadExtension.appex Bundle IDs: App = AtlasDrift.SnapTrail, Extension = AtlasDrift.SnapTrail.BackgroundDownloadExtension (correct parent-child pattern) Extension point: com.apple.background-asset-downloader-extension Product type: com.apple.product-type.extensionkit-extension Protocol: StoreDownloaderExtension from StoreKit (for Apple-hosted packs) App group: group.AtlasDrift.SnapTrail (matching in both app and extension entitlements) Info.plist keys: BAAppGroupID, BAHasManagedAssetPacks = YES BAUsesAppleHosting = YES (no BAInitialDownloadRestrictions or other BA keys) .aar Packaging Archives built with xcrun ba-package from the Assets directory. Manifest format: { "assetPackID": "ireland", "downloadPolicy": { "onDemand": {} }, "fileSelectors": [{ "directory": "POIRegions/ireland/IR" }], "platforms": ["iOS"] } Uploaded via App Store Connect API with assetType: "ASSET". Diagnostic Observations AssetPackManager.shared.assetPack(withID:) returns valid metadata (correct download size) ensureLocalAvailability(of:) completes without error assetPackIsAvailableLocally(withID:) returns true url(for: FilePath(".")) returns a URL that exists but has zero children (empty namespace) contents(at:) returns fileNotFound for all path variants tested The extension never runs — breadcrumb file written in init() is never created The -10814 error appears in daemon logs for every download cycle Questions Has anyone successfully used Apple-Hosted Managed Background Assets on iOS 26 beta? Is the daemon's LaunchServices integration known to be broken in this seed? Is there anything about the bundle identifier format or provisioning profile setup that could cause the BA daemon's LS lookup to fail, even though the app installs and runs fine otherwise? Are there any additional Info.plist keys or entitlements beyond what's documented that might be required for the daemon to locate the app bundle? Any guidance would be appreciated. I've filed a Feedback report with the full sysdiagnose attached.
1
0
300
3w
Recommended Architecture for Near-Real-Time Local Device Monitoring in Background
Hello, We are designing an iOS application for a vehicle safety use case. The app connects to a local network device (a DVR installed in the vehicle) and processes image frames to detect passenger-left-behind items, then alerts the driver if needed. We would like to better understand the recommended and App Store-compliant architecture for handling this scenario, especially when the app is not in the foreground. Current Requirements The app communicates with a local network device over Wi-Fi The device can provide image data The app performs or triggers AI inference based on the received data When a relevant event is detected, the app needs to notify the user (e.g., audio alert) Questions Background Execution Model For a near-real-time monitoring scenario, what architectural patterns are recommended on iOS when the app is running in the background? Background Modes Consideration In this type of use case, are any existing background modes (such as location or external accessory) considered appropriate when used strictly within their intended purpose? Enterprise / Managed Deployment Are there any specific entitlements or capabilities available in enterprise or commercial deployments that may allow more persistent local network communication under certain conditions?
1
0
143
Apr ’26
applicationWillTerminate to wrap up Background Recording
Hello together, the user is able to do recordings with my app. The recordings also runs, while the App is in Background. I have Background Modes Audio & Background enabled. When the user accidentally terminates the App while the recording is still running, the whole recording is lost. I tried AppDelegate applicationWillTerminate on my iOS 26 App and it works perfectly to wrap up the LiveActivity that is shown while the recording is active. But it does not save the Audio and also doesn't update the Widgets (they are interactive and show a different state while recording and stay stuck in recording-state on accidental termination). Any ideas? Best wishes, Dominik
2
0
279
3w
SwiftData with CloudKit Error: Error updating background task request
Hi, Overview I have a SwiftData project which automatically syncs with CloudKit. When I run the app, I see the following error in Xcode logs. Error updating background task request: Error Domain=BGSystemTaskSchedulerErrorDomain Code=3 "(null)" My attempt I can enable Background processing (under Signing & Capabilities > Background modes), but I don't know the BGTaskSchedulerPermittedIdentifiers to add in the Info.plist Questions How can I resolve this? If I should enable background processing, what are the BGTaskSchedulerPermittedIdentifiers to add in Info.plist?
18
0
970
1w
Safari web extensions: Optimal IPC architecture between extension and the containing app
I'm building a macOS safari extension and porting its functionality from a chrome extension. The chrome extension uses native messaging hosts to communicate with another process using IPC and holding a persistent connection. To use the same functionality in Safari, I understand that will need to use the handler to communicate it to the containing app, and the app will have to hold the persistent IPC connection. My question derives from that concept: should the app be running in a long-lived state? And if so, how can I ensure that app be running 100% of the time. Also is there any way I can control it's lifecycle with the Safari browser's lifecycle? I will not be using XPC here, but a different UDS to make the connection. Also in addition to that, what would you recommend the best approach is the communicate between the extension and it's handler? -> should it be again a UDS or userDefaults +darwin notification be enough? Also I wouldn't want the inter-message relayed between components to be dropped, is there a fault tolerant architecture you would recommend?
0
0
246
Apr ’26
HealthKit Background Sync: How Close to Real-Time Can We Reliably Get?
I am building an iOS mobile application using Flutter, with native Swift integration for accessing Apple HealthKit instead of a Flutter plugin. The primary goal is to capture and sync specific HealthKit data types, namely Respiratory Rate and Sleeping Wrist Temperature, and send this data to a backend API as close to real-time as possible after it is written to HealthKit. The application needs to support both foreground and background syncing. Data should be synced when the app is opened, but also in the background when the device is locked. Additionally, there are reliability constraints to consider: the user may not open the app for extended periods, the device may remain locked, and Low Power Mode or other system restrictions may impact background execution. I have explored a few possible approaches. One option is using BGTaskScheduler to periodically fetch and sync data. However, based on my understanding, background tasks are not guaranteed to execute frequently and may be throttled or stopped by the system after some time. Another approach is to use HKObserverQuery along with HKAnchoredObjectQuery. In this setup, observer queries would be registered for the required data types, background delivery would be enabled, and whenever triggered, anchored queries would fetch incremental updates which would then be sent to the backend. This seems closer to a real-time model, but I am unsure how reliable and timely these background updates are in practice. I have also looked into newer APIs like HKQueryDescriptor, but it is not clear whether they provide any advantage over the observer plus anchored query approach for this use case. My main questions are: what is the recommended architecture for achieving near real-time syncing of HealthKit data for these metrics? Does HealthKit background delivery provide any guarantees or expectations around delivery timing, or can updates be significantly delayed depending on system conditions? How should edge cases be handled, such as when the device remains locked for long durations or when Low Power Mode is enabled? Would it be advisable to combine observer queries with BGTaskScheduler as a fallback mechanism? Finally, apps like Athlytic appear to show updated data immediately when opened. I am curious whether this is primarily achieved through background delivery or by fetching data on demand when the app becomes active. The goal is to design a system that is as close to real-time as possible while remaining reliable and compliant with iOS background execution constraints. Any recommended patterns, best practices, or references would be greatly appreciated.
1
0
253
3w
iOS 26.5 SIGKILLs audio-recording app at ~50s of background despite UIBackgroundModes: audio - what is the supported API path?
Hi, hoping for guidance on what's a long-running bug for our app. The problem We have a transcription app on iPhone 17 Pro Max running iOS 26.5. Recording flow uses AVAudioEngine.installTap(onBus:) to capture PCM into a JS bridge for streaming to a remote transcription service. A parallel AVAudioRecorder writes the same audio to disk as backup. When the user starts a recording and locks the phone, iOS terminates our process with SIGKILL at approximately 50 seconds of continuous background time, despite: UIBackgroundModes includes audio (verified in shipping IPA's Info.plist) AVAudioSession.setCategory(.playAndRecord, mode: .default) is active AVAudioEngine is running with installTap producing PCM buffers right up to the moment of death UIApplication.backgroundTimeRemaining returns Double.greatestFiniteMagnitude at applicationDidEnterBackground (verified in our event log) No AVAudioSession.interruptionNotification is delivered before the kill. iOS terminates the process cleanly with no warning event to our observer. Evidence Our Swift observer module writes an event log to disk on every system event. On relaunch we ship it to our crash reporter. Excerpt from a recent kill on iOS 26.5 / build 2.1.32: T=0.000s session-start (engineRunning: true) T=57.199s app-will-resign-active (bufferCallbackCount: 22) T=58.913s app-did-enter-background (backgroundTimeRemaining: infinity, bufferCallbackCount: 39) [no further audio events captured] [Swift heartbeat written every 5s for next ~46 seconds] T~105s Process SIGKILLed (heartbeat last-alive: 09:31:01.597Z) Background time before kill: ~46 seconds. engineRunning: true and bufferCallbackCount was still incrementing at the moment the event log stops capturing - the audio engine was alive and feeding buffers when iOS terminated us. What we've tried (35 documented attempts) Hopefully not all relevant but listing for completeness: Various AVAudioSession category/mode/options combinations (Default, Measurement, VoiceChat, .mixWithOthers, .defaultToSpeaker, .allowBluetoothHFP) Parallel AVAudioRecorder writing a .caf file as a "real recording app" signal SFSpeechRecognizer with requiresOnDeviceRecognition = true consuming PCM in-process (50s request rotation) BGContinuedProcessingTask with Progress.completedUnitCount reporting monotonic progress every 5 seconds Live Activity (ActivityKit) with NSSupportsLiveActivitiesFrequentUpdates = true Live Activity update pushes via APNs (confirmed wake widget extension only, not host) Silent device-token APNs background pushes (confirmed iOS ~5/day rate limit) CallKit fake call (CXProvider + CXCallController) - works but creates the green pill UI which our product can't ship WebRTC peer connection with active media stream (via react-native-webrtc loopback) UIBackgroundModes: voip declaration (without CallKit) beginBackgroundTask + engine bounce (Apple's own guidance says don't, our test confirmed it's actively harmful) CLLocationManager background updates All die at ~50s background. None of them survive. What works on the same device Three App Store transcription apps survive indefinite background recording on our exact device + iOS version. We have inspected their IPAs (Mach-O LC_LOAD_DYLIB analysis + embedded entitlement extraction): Otter (com.aisense.otter) - UIBackgroundModes: audio + fetch + processing + remote-notification. Uses OneSignal-driven Live Activity push tokens + NotificationServiceExtension. No CallKit, PushKit, or WebRTC. Granola (com.granola.ios-prod) - has UIBackgroundModes: voip but the voip is for their separate outbound-phone-call feature (TwilioVoice + CallKit, lives in their PhoneCalls.framework). Recording-path uses ONLY AVAudioRecorder + PlayAndRecord + ModeDefault + Live Activity with frequentPushesEnabled. Zero PushKit anywhere in the bundle. Transcribe Speech to Text by DENIVIP (ru.denivip.transcribe) - the smallest API surface: UIBackgroundModes: audio + remote-notification only. AVAudioEngine + .playAndRecord + .default + SFSpeechRecognizer consuming PCM. No CallKit, PushKit, BGTask, Live Activity, WebRTC, or VoIP. Three apps, three different mechanisms, all working. We've implemented bits of all three approaches in our app and still die at 50s. Apple Voice Memos (system app, private entitlements) also survives indefinite recording on the same device. Questions What is the supported API path for indefinite background microphone-only recording on iOS 26.5? Voice Memos and competitor apps clearly accomplish this - what's the missing piece? Why does UIApplication.backgroundTimeRemaining return Double.greatestFiniteMagnitude at applicationDidEnterBackground but the process is terminated ~50 seconds later? Is the meaning of this property changing in iOS 26? What causes the iOS 26 process scheduler to revoke the audio-mode background runtime classification? No AVAudioSession.interruptionNotification is delivered before SIGKILL. Where can we observe the classification change? Does iOS 26 distinguish "audio recording with no audible output" from "audio recording with audible output (e.g. a media playback session)"? If so, what is the supported API to register as a recording-only background-audio app? Does BGContinuedProcessingTask (new in iOS 26) actually extend background CPU time for an app that is also using UIBackgroundModes: audio and an active AVAudioSession? Or is it for finish-what-you-started bursts only (per WWDC 2025 session 227)? Any guidance - even pointers to specific WWDC sessions, sample code, or technotes - would be hugely appreciated. We've spent ~40+ hours on this and want to know what the supported path looks like in iOS 26. Happy to share more event-log data, IPA inspection notes, or build a focused Xcode reproduction if helpful. Thanks!
1
0
214
1w
iOS feasibility question: user-initiated wake-word detection during active session
Hi all, Technical architecture question for those experienced with iOS background audio / microphone constraints. I’m exploring an app concept where: the user explicitly starts a temporary active session during that session, on-device wake-word / keyword detection runs locally no audio is stored or transmitted during passive monitoring monitoring stops when the user ends the session The intended UX is that the user may then lock the phone or place it away while the active session remains in progress. Question: Is there any App Store-compliant architecture that would allow local keyword / wake-word detection to continue while the device is locked or the app is backgrounded during that active session? Or would iOS lifecycle / background execution rules make this infeasible for custom wake-word detection? Interested in practical experience around: AVAudioSession background audio modes on-device speech processing App Review acceptability Thanks in advance.
0
0
297
2w
Background Location Tracking Not Reliably Relaunching App After Termination
We are developing a mileage tracking application that depends on continuous background location updates on iOS. Our app has the required background modes enabled: <key>UIBackgroundModes</key> <array> <string>remote-notification</string> <string>processing</string> <string>fetch</string> <string>location</string> </array> We are observing inconsistent behavior with background location tracking in app terminated state. In some cases, after a period of time, location updates stop completely. Sometimes iOS successfully relaunches the app when movement is detected and location updates resume correctly. However, in other cases, the app is not relaunched by the system, and we stop receiving location updates entirely. We reviewed Apple’s documentation on handling background location updates: https://developer.apple.com/documentation/corelocation/handling-location-updates-in-the-background Based on our observations, we would appreciate clarification on the following points: Is this considered expected iOS behavior or a system limitation? Under what conditions does iOS decide not to relaunch a terminated app for location events? Are there recommended best practices to improve the reliability of background location relaunch behavior? Is there any logging, diagnostics, or debugging mechanism available to determine why the app was not relaunched? Apple’s documentation mentions that location updates may be queued while the app is terminated and later delivered after relaunch. However, in some scenarios we do not receive those queued updates after the app restarts. Under what conditions can queued location updates be discarded or not delivered? Additional notes: We are using standard Core Location background updates. “Always” location permission is granted. Background App Refresh is enabled. The issue is observed intermittently across multiple iOS devices.
4
0
236
1d
Seeking Apple Recommended Solution for Extended, Deterministic Background Sync/Upload for Offline-First App (Large Data)
Context Our enterprise application is offline-first for iOS and iPadOS, designed to work completely offline, storing a very large local database (DB) and many attached files (images and videos) locally. Users create and update entities on the device.1 When connectivity is available, the app performs a bidirectional sync: local changes (including multi-gigabyte files) are uploaded, and thousands of DB updates are pulled down and applied locally. The Challenge: Foreground Requirement The complete sync process often requires 10 to 20 minutes to finish. Users expect their devices to proactively sync when online, even if it takes this long. Our fundamental problem is that, at present, users must keep the app in the foreground to complete the task. We have confirmed that on iOS, the system aggressively terminates the app process, typically after 30 seconds of being sent to the background. We currently advise users with large projects to keep the app in the foreground and connected to power.2 Existing Mitigation and Technical Details We have implemented several best practices to optimize transfers and manage device resources: We use battery checks before initiating large transfers, with a low battery threshold (around 15%) to pause actions if the device will enter a danger zone.2 Our upload mechanism uses HTTP Range Requests to implement a resumable single-stream approach for maximum throughput, ensuring that if a connection drops mid-transfer (even at 1.2 GB of a 2.5 GB file), we only re-transfer the remaining bytes, rather than losing all progress. This addresses network resilience and speed but not the OS background limitation.3 The Core Issue The various background options provided by iOS and iPadOS do not appear deterministic enough to reliably handle the immediate, extended data synchronization (uploading GB files and pulling down substantial DB changes) that we require. We are seeking a solution where a user-initiated task engages in background work almost immediately, reliably continuing for 10–20+ minutes after the user leaves the app or locks the screen, allowing for more "natural" device usage. Our Question for Apple Engineering Given the high volume of data transfer and the need for deterministic, extended background execution, what is Apple's current recommended, official approach for an enterprise app that requires prolonged background syncs—specifically, how can we architect this on iOS/iPadOS to reliably continue the upload and download of large data sets and database updates after the app moves out of the foreground?
2
0
70
4d
Sleep onset detection on watchOS: viable non-workout paths and CMSensorRecorder behavior
I'm building a sleep tracker for couples — the headline feature is a notification to your partner the moment you fall asleep (and another when you wake up), detected on the Apple Watch from accelerometer and heart-rate data. The detection has to happen within minutes of onset for the product to make sense. My setup HKObserverQuery on heart rate with enableBackgroundDelivery(.immediate), re-registered on foreground. WKApplicationRefreshBackgroundTask rescheduled every 15 minutes. CMSensorRecorder.recordAccelerometer(forDuration: 12 * 3600) re-armed on every wake. A van Hees-style stillness classifier reading the last ~35 minutes of the buffer, with heart rate as a soft confirmer. HealthKit and Motion & Fitness authorized on both iPhone and watch. The observer's completionHandler() is called on every branch and the handler stays well under the 15-second watchdog. No HKWorkoutSession as my app is not a workout. Questions Is CMSensorRecorder paused or deprioritized while the Apple Watch's automatic sleep detection has classified the user as asleep? On a worn watch with the recorder armed for 12 hours, accelerometerData(from:to:) over a 35-minute window inside the auto-detected sleep period returns zero samples. The exact same call an hour later, once the watch has decided the user is awake, returns roughly ten thousand samples for an equivalent window. The user never activated Sleep Focus or Theater Mode — the only sleep-related state at play is the watch's own automatic detection, the same one that writes Core / REM / Deep stages into Apple Health. Is this documented power management I missed, or is it unexpected? Happy to file Feedback with a sysdiagnose during the window if you confirm it shouldn't behave this way. Is there a sanctioned non-workout path on current watchOS for detecting sleep onset within a few minutes of it happening? A full night recently produced a five-hour stretch with zero observer callbacks and zero background-refresh deliveries between bedtime and wake. The historical guidance to third-party sleep apps has been to reconstruct nights post-hoc from sleepAnalysis samples rather than attempt live detection. Is that still the recommendation today, or is there an API I've missed that would give an onset-focused app tighter wakes around bedtime? What is the current App Store review stance on HKWorkoutSession for sleep tracking? Would an app that auto-starts a .other / indoor workout only when its own classifier detects pre-sleep signals at the user's typical bedtime, ends the session as soon as onset is confirmed, never starts one outside that gated condition, and explicitly discloses "sleep tracking via workout session" in the App Store metadata — be an acceptable pattern, or grounds for rejection regardless of disclosure?
1
0
72
2d
Background Termination Investigation
Hello, We are currently investigating an issue where our app is being terminated by the system while running in the background. At the moment, the app does not perform any significant background activity, and memory usage remains relatively low (approximately 150–200 MB). Despite this, the app is still being terminated in the background, even under conditions where other apps appear to remain active. From our investigation so far, the issue does not appear to be related to: High memory consumption Explicit background task misuse Application crashes on our side For additional context, we had previously used silent push notifications to trigger heavy upload operations in the background. Since we suspected this behavior might be contributing to the issue, we completely stopped using this mechanism approximately two weeks ago. However, the background terminations are still occurring. We would like to better understand the possible causes of this behavior. Specifically, could this be related to: Watchdog terminations Background assertion or lifecycle violations RunningBoard resource management Jetsam policies Background execution timeouts Any other system-level resource or process management constraints We would greatly appreciate any guidance on how to identify the root cause or which logs/diagnostics we should focus on to further investigate the issue. Thank you.
2
0
126
1d
Live Activity Stops Updating After 30 Seconds in Background During Audio Playback
Hi I developed a music app that plays offline audio and displays lyrics using Live Activities. According to ActivityKit documentation, Live Activities can be updated from the background. However, in my case, updates stop after ~30 seconds when the app goes to the background or the device is locked. Important points: The app continues running in the background (audio playback works fine using AVAudioSession with .playback) Background code execution is working as expected Only the Live Activity stops updating I am not using push updates since this is an offline app. Is there any limitation or requirement for updating Live Activities continuously in the background during audio playback? Audio Session Configuration let session = AVAudioSession.sharedInstance() try session.setCategory( .playback, mode: .default, options: [.mixWithOthers] // ✅ DO NOT interrupt other audio ) try session.setActive(true) print("✅ [AudioSession] Activated with mixWithOthers") } catch { print("❌ [AudioSession] Error: \(error)") } Live Activity Update Methods guard let activity = getLiveActivity(for: recordID) else{ print("⚠️ No Live Activity found for recordID: \(recordID)") return } guard activity.activityState == .active else { print("⚠️ Activity is not active") return } Task { let content = ActivityContent( state: state, staleDate: Date().addingTimeInterval(60 * 60 * 12), relevanceScore: 1.0 ) await activity.update(content) print("✅ Live Activity updated with ActivityContent") } }
Replies
0
Boosts
0
Views
400
Activity
Apr ’26
SwiftUI View Not Initialized on Background Relaunch (CoreBluetooth / Cold Start?)
I have a question regarding cold start and pre-warming behavior on iOS. I’m developing a SwiftUI app that continuously receives data from a BLE device in the background. We’ve observed that after the BLE stream stops, the OS often terminates our app. Later, when the sensor comes back into range, iOS appears to relaunch (or reinitialize) the app. In our app, we use a WindowGroup like this: WindowGroup { AppView(store: store) } We’ve placed our BLE reconnection logic inside a .task modifier in AppView. What’s confusing is this: Most of the time, when the app is relaunched, AppView is created and the .task runs as expected. However, in about 1 out of 10 cases, AppView is not created at all, so the .task does not execute. I’m trying to understand: Under what conditions does iOS relaunch an app without fully initializing the SwiftUI view hierarchy? Is this related to pre-warming or background relaunch mechanisms (e.g., CoreBluetooth state restoration)? What determines whether the WindowGroup and root view are actually instantiated? Any insight into the system’s relaunch behavior or lifecycle in this scenario would be greatly appreciated.
Replies
2
Boosts
0
Views
227
Activity
Apr ’26
HKObserverQuery BackgroundDelivery not executed
Hi, I'm having the same issue described in https://developer.apple.com/forums/thread/690974?page=2. When connected to Xcode or when the app is in the foreground, HKObserverQuery fires correctly and my app processes step updates. But once disconnected from Xcode, background delivery stops completely and the observer callback is never called. My setup: com.apple.developer.healthkit.background-delivery entitlement is present and in the provisioning profile enableBackgroundDelivery(for: .stepCount, frequency: .immediate) returns success = true HKObserverQuery is registered on every launch including background launches I also have CMPedometer.startEventUpdates running as a supplemental trigger Background Modes includes "Background fetch" and "Background processing" Device: iPhone, iOS 17.4+ App type: App uses Screen Time / Family Controls (ManagedSettings) to block apps until a step goal is met Has anyone found a reliable fix? Any feedback from Apple engineers would be appreciated.
Replies
1
Boosts
0
Views
369
Activity
Apr ’26
Clarification on HealthKit Observer Delivery Frequency and BGTaskScheduler Behavior
Hi Team, We are implementing HealthKit data sync using HKObserverQuery along with enableBackgroundDelivery and BGTaskScheduler for fallback processing. However, we are observing inconsistent behavior and would like clarification on expected system behavior: For HKObserverQuery: When using enableBackgroundDelivery with frequency .immediate, we sometimes receive updates promptly, but other times we do not receive any trigger at all. Similarly, when using .hourly, our expectation was that updates would be delivered approximately once per hour, but in practice, triggers are delayed, batched, or skipped. For BGTaskScheduler: We are scheduling BGAppRefreshTask with earliestBeginDate set (e.g., 1 hour), but tasks are sometimes delayed by several hours or not triggered predictably. In some cases, tasks are not executed even after extended periods. We would like to understand: Are HKObserverQuery delivery frequencies (.immediate, .hourly, .daily) strictly best-effort hints rather than guaranteed intervals? Under what conditions can observer updates be skipped or significantly delayed? Is there any recommended approach to ensure more reliable periodic syncing of HealthKit data? For BGTaskScheduler, what factors most strongly influence scheduling delays or missed executions? Our goal is to design a reliable sync mechanism, but the lack of deterministic behavior is making it difficult to define expected system behavior. Any clarification or recommended best practices would be greatly appreciated. Thanks in advance!
Replies
1
Boosts
0
Views
301
Activity
Apr ’26
Receiving MPMusicPlayerController playback notifications when app is suspended
Heyy, I'm building a music tracking app that logs a user's Apple Music plays to build a personal weekly chart. The core mechanic depends on accurately counting how many times a user plays each track. My current implementation uses MPMusicPlayerController.systemMusicPlayer with beginGeneratingPlaybackNotifications() and observes MPMusicPlayerControllerNowPlayingItemDidChange. This works well when the app is in the foreground or recently backgrounded, but notifications stop firing once iOS suspends the app. To get around this I've implemented: applicationDidBecomeActive - restarts the monitor and logs the currently playing track on every foreground Background fetch (performFetchWithCompletionHandler) - periodically wakes the app to log what's playing. This gives some coverage but misses plays that happen between background fetch intervals or when the user hasn't opened the app in a while. The result is an inaccurate play count which undermines the core feature. My questions: Is there a supported entitlement or capability that would allow an app to receive MPMusicPlayerController playback notifications while suspended? Is MusicKit or MediaPlayer the recommended framework for this use case, or is there a better API I'm not aware of? Are there any supported background modes that would keep playback notification delivery alive without requiring the app to be a full audio player? I've looked at MusicRecentlyPlayedRequest but it only returns the last 25 items with no play counts, so it can't tell me a track was played 10 times vs once. Any guidance on the right approach here would be really appreciated.
Replies
2
Boosts
0
Views
232
Activity
Apr ’26
Background Assets: Downloaded .aar not working — "bundle record couldn't be looked up" error (-10814)
Platform: iOS 26 (23E254) Xcode: 26.0 Reproduces on: Debug builds AND TestFlight Summary: I'm using Apple-Hosted Managed Background Assets with on-demand download policy. The .aar archives download successfully (correct file size, status = downloaded), but the contents are never extracted into the asset pack namespace. AssetPackManager.shared.contents(at:) returns fileNotFound for all path variants, and url(for: FilePath(".")) returns a URL that exists but contains zero children. Root Cause from Sysdiagnose: The backgroundassets.user daemon logs reveal this error on every download attempt: A bundle record couldn't be looked up for the application identifier "AtlasDrift.SnapTrail": Error Domain=NSOSStatusErrorDomain Code=-10814 "(null)" UserInfo={_LSFile=LSBindingEvaluator.mm, _LSLine=1973, _LSFunction=runEvaluator} Error code -10814 is kLSApplicationNotFoundErr. The BA daemon downloads the .aar blob, then attempts to find the app bundle via LaunchServices to locate the extension for extraction — but the LS lookup fails. Without the extension, extraction never occurs. Verified Configuration Everything matches the documentation and WWDC sessions: Extension embedded at SnapTrail.app/Extensions/BackgroundDownloadExtension.appex Bundle IDs: App = AtlasDrift.SnapTrail, Extension = AtlasDrift.SnapTrail.BackgroundDownloadExtension (correct parent-child pattern) Extension point: com.apple.background-asset-downloader-extension Product type: com.apple.product-type.extensionkit-extension Protocol: StoreDownloaderExtension from StoreKit (for Apple-hosted packs) App group: group.AtlasDrift.SnapTrail (matching in both app and extension entitlements) Info.plist keys: BAAppGroupID, BAHasManagedAssetPacks = YES BAUsesAppleHosting = YES (no BAInitialDownloadRestrictions or other BA keys) .aar Packaging Archives built with xcrun ba-package from the Assets directory. Manifest format: { "assetPackID": "ireland", "downloadPolicy": { "onDemand": {} }, "fileSelectors": [{ "directory": "POIRegions/ireland/IR" }], "platforms": ["iOS"] } Uploaded via App Store Connect API with assetType: "ASSET". Diagnostic Observations AssetPackManager.shared.assetPack(withID:) returns valid metadata (correct download size) ensureLocalAvailability(of:) completes without error assetPackIsAvailableLocally(withID:) returns true url(for: FilePath(".")) returns a URL that exists but has zero children (empty namespace) contents(at:) returns fileNotFound for all path variants tested The extension never runs — breadcrumb file written in init() is never created The -10814 error appears in daemon logs for every download cycle Questions Has anyone successfully used Apple-Hosted Managed Background Assets on iOS 26 beta? Is the daemon's LaunchServices integration known to be broken in this seed? Is there anything about the bundle identifier format or provisioning profile setup that could cause the BA daemon's LS lookup to fail, even though the app installs and runs fine otherwise? Are there any additional Info.plist keys or entitlements beyond what's documented that might be required for the daemon to locate the app bundle? Any guidance would be appreciated. I've filed a Feedback report with the full sysdiagnose attached.
Replies
1
Boosts
0
Views
300
Activity
3w
Recommended Architecture for Near-Real-Time Local Device Monitoring in Background
Hello, We are designing an iOS application for a vehicle safety use case. The app connects to a local network device (a DVR installed in the vehicle) and processes image frames to detect passenger-left-behind items, then alerts the driver if needed. We would like to better understand the recommended and App Store-compliant architecture for handling this scenario, especially when the app is not in the foreground. Current Requirements The app communicates with a local network device over Wi-Fi The device can provide image data The app performs or triggers AI inference based on the received data When a relevant event is detected, the app needs to notify the user (e.g., audio alert) Questions Background Execution Model For a near-real-time monitoring scenario, what architectural patterns are recommended on iOS when the app is running in the background? Background Modes Consideration In this type of use case, are any existing background modes (such as location or external accessory) considered appropriate when used strictly within their intended purpose? Enterprise / Managed Deployment Are there any specific entitlements or capabilities available in enterprise or commercial deployments that may allow more persistent local network communication under certain conditions?
Replies
1
Boosts
0
Views
143
Activity
Apr ’26
applicationWillTerminate to wrap up Background Recording
Hello together, the user is able to do recordings with my app. The recordings also runs, while the App is in Background. I have Background Modes Audio & Background enabled. When the user accidentally terminates the App while the recording is still running, the whole recording is lost. I tried AppDelegate applicationWillTerminate on my iOS 26 App and it works perfectly to wrap up the LiveActivity that is shown while the recording is active. But it does not save the Audio and also doesn't update the Widgets (they are interactive and show a different state while recording and stay stuck in recording-state on accidental termination). Any ideas? Best wishes, Dominik
Replies
2
Boosts
0
Views
279
Activity
3w
SwiftData with CloudKit Error: Error updating background task request
Hi, Overview I have a SwiftData project which automatically syncs with CloudKit. When I run the app, I see the following error in Xcode logs. Error updating background task request: Error Domain=BGSystemTaskSchedulerErrorDomain Code=3 "(null)" My attempt I can enable Background processing (under Signing & Capabilities > Background modes), but I don't know the BGTaskSchedulerPermittedIdentifiers to add in the Info.plist Questions How can I resolve this? If I should enable background processing, what are the BGTaskSchedulerPermittedIdentifiers to add in Info.plist?
Replies
18
Boosts
0
Views
970
Activity
1w
Safari web extensions: Optimal IPC architecture between extension and the containing app
I'm building a macOS safari extension and porting its functionality from a chrome extension. The chrome extension uses native messaging hosts to communicate with another process using IPC and holding a persistent connection. To use the same functionality in Safari, I understand that will need to use the handler to communicate it to the containing app, and the app will have to hold the persistent IPC connection. My question derives from that concept: should the app be running in a long-lived state? And if so, how can I ensure that app be running 100% of the time. Also is there any way I can control it's lifecycle with the Safari browser's lifecycle? I will not be using XPC here, but a different UDS to make the connection. Also in addition to that, what would you recommend the best approach is the communicate between the extension and it's handler? -> should it be again a UDS or userDefaults +darwin notification be enough? Also I wouldn't want the inter-message relayed between components to be dropped, is there a fault tolerant architecture you would recommend?
Replies
0
Boosts
0
Views
246
Activity
Apr ’26
HealthKit Background Sync: How Close to Real-Time Can We Reliably Get?
I am building an iOS mobile application using Flutter, with native Swift integration for accessing Apple HealthKit instead of a Flutter plugin. The primary goal is to capture and sync specific HealthKit data types, namely Respiratory Rate and Sleeping Wrist Temperature, and send this data to a backend API as close to real-time as possible after it is written to HealthKit. The application needs to support both foreground and background syncing. Data should be synced when the app is opened, but also in the background when the device is locked. Additionally, there are reliability constraints to consider: the user may not open the app for extended periods, the device may remain locked, and Low Power Mode or other system restrictions may impact background execution. I have explored a few possible approaches. One option is using BGTaskScheduler to periodically fetch and sync data. However, based on my understanding, background tasks are not guaranteed to execute frequently and may be throttled or stopped by the system after some time. Another approach is to use HKObserverQuery along with HKAnchoredObjectQuery. In this setup, observer queries would be registered for the required data types, background delivery would be enabled, and whenever triggered, anchored queries would fetch incremental updates which would then be sent to the backend. This seems closer to a real-time model, but I am unsure how reliable and timely these background updates are in practice. I have also looked into newer APIs like HKQueryDescriptor, but it is not clear whether they provide any advantage over the observer plus anchored query approach for this use case. My main questions are: what is the recommended architecture for achieving near real-time syncing of HealthKit data for these metrics? Does HealthKit background delivery provide any guarantees or expectations around delivery timing, or can updates be significantly delayed depending on system conditions? How should edge cases be handled, such as when the device remains locked for long durations or when Low Power Mode is enabled? Would it be advisable to combine observer queries with BGTaskScheduler as a fallback mechanism? Finally, apps like Athlytic appear to show updated data immediately when opened. I am curious whether this is primarily achieved through background delivery or by fetching data on demand when the app becomes active. The goal is to design a system that is as close to real-time as possible while remaining reliable and compliant with iOS background execution constraints. Any recommended patterns, best practices, or references would be greatly appreciated.
Replies
1
Boosts
0
Views
253
Activity
3w
iOS 26.5 SIGKILLs audio-recording app at ~50s of background despite UIBackgroundModes: audio - what is the supported API path?
Hi, hoping for guidance on what's a long-running bug for our app. The problem We have a transcription app on iPhone 17 Pro Max running iOS 26.5. Recording flow uses AVAudioEngine.installTap(onBus:) to capture PCM into a JS bridge for streaming to a remote transcription service. A parallel AVAudioRecorder writes the same audio to disk as backup. When the user starts a recording and locks the phone, iOS terminates our process with SIGKILL at approximately 50 seconds of continuous background time, despite: UIBackgroundModes includes audio (verified in shipping IPA's Info.plist) AVAudioSession.setCategory(.playAndRecord, mode: .default) is active AVAudioEngine is running with installTap producing PCM buffers right up to the moment of death UIApplication.backgroundTimeRemaining returns Double.greatestFiniteMagnitude at applicationDidEnterBackground (verified in our event log) No AVAudioSession.interruptionNotification is delivered before the kill. iOS terminates the process cleanly with no warning event to our observer. Evidence Our Swift observer module writes an event log to disk on every system event. On relaunch we ship it to our crash reporter. Excerpt from a recent kill on iOS 26.5 / build 2.1.32: T=0.000s session-start (engineRunning: true) T=57.199s app-will-resign-active (bufferCallbackCount: 22) T=58.913s app-did-enter-background (backgroundTimeRemaining: infinity, bufferCallbackCount: 39) [no further audio events captured] [Swift heartbeat written every 5s for next ~46 seconds] T~105s Process SIGKILLed (heartbeat last-alive: 09:31:01.597Z) Background time before kill: ~46 seconds. engineRunning: true and bufferCallbackCount was still incrementing at the moment the event log stops capturing - the audio engine was alive and feeding buffers when iOS terminated us. What we've tried (35 documented attempts) Hopefully not all relevant but listing for completeness: Various AVAudioSession category/mode/options combinations (Default, Measurement, VoiceChat, .mixWithOthers, .defaultToSpeaker, .allowBluetoothHFP) Parallel AVAudioRecorder writing a .caf file as a "real recording app" signal SFSpeechRecognizer with requiresOnDeviceRecognition = true consuming PCM in-process (50s request rotation) BGContinuedProcessingTask with Progress.completedUnitCount reporting monotonic progress every 5 seconds Live Activity (ActivityKit) with NSSupportsLiveActivitiesFrequentUpdates = true Live Activity update pushes via APNs (confirmed wake widget extension only, not host) Silent device-token APNs background pushes (confirmed iOS ~5/day rate limit) CallKit fake call (CXProvider + CXCallController) - works but creates the green pill UI which our product can't ship WebRTC peer connection with active media stream (via react-native-webrtc loopback) UIBackgroundModes: voip declaration (without CallKit) beginBackgroundTask + engine bounce (Apple's own guidance says don't, our test confirmed it's actively harmful) CLLocationManager background updates All die at ~50s background. None of them survive. What works on the same device Three App Store transcription apps survive indefinite background recording on our exact device + iOS version. We have inspected their IPAs (Mach-O LC_LOAD_DYLIB analysis + embedded entitlement extraction): Otter (com.aisense.otter) - UIBackgroundModes: audio + fetch + processing + remote-notification. Uses OneSignal-driven Live Activity push tokens + NotificationServiceExtension. No CallKit, PushKit, or WebRTC. Granola (com.granola.ios-prod) - has UIBackgroundModes: voip but the voip is for their separate outbound-phone-call feature (TwilioVoice + CallKit, lives in their PhoneCalls.framework). Recording-path uses ONLY AVAudioRecorder + PlayAndRecord + ModeDefault + Live Activity with frequentPushesEnabled. Zero PushKit anywhere in the bundle. Transcribe Speech to Text by DENIVIP (ru.denivip.transcribe) - the smallest API surface: UIBackgroundModes: audio + remote-notification only. AVAudioEngine + .playAndRecord + .default + SFSpeechRecognizer consuming PCM. No CallKit, PushKit, BGTask, Live Activity, WebRTC, or VoIP. Three apps, three different mechanisms, all working. We've implemented bits of all three approaches in our app and still die at 50s. Apple Voice Memos (system app, private entitlements) also survives indefinite recording on the same device. Questions What is the supported API path for indefinite background microphone-only recording on iOS 26.5? Voice Memos and competitor apps clearly accomplish this - what's the missing piece? Why does UIApplication.backgroundTimeRemaining return Double.greatestFiniteMagnitude at applicationDidEnterBackground but the process is terminated ~50 seconds later? Is the meaning of this property changing in iOS 26? What causes the iOS 26 process scheduler to revoke the audio-mode background runtime classification? No AVAudioSession.interruptionNotification is delivered before SIGKILL. Where can we observe the classification change? Does iOS 26 distinguish "audio recording with no audible output" from "audio recording with audible output (e.g. a media playback session)"? If so, what is the supported API to register as a recording-only background-audio app? Does BGContinuedProcessingTask (new in iOS 26) actually extend background CPU time for an app that is also using UIBackgroundModes: audio and an active AVAudioSession? Or is it for finish-what-you-started bursts only (per WWDC 2025 session 227)? Any guidance - even pointers to specific WWDC sessions, sample code, or technotes - would be hugely appreciated. We've spent ~40+ hours on this and want to know what the supported path looks like in iOS 26. Happy to share more event-log data, IPA inspection notes, or build a focused Xcode reproduction if helpful. Thanks!
Replies
1
Boosts
0
Views
214
Activity
1w
iOS feasibility question: user-initiated wake-word detection during active session
Hi all, Technical architecture question for those experienced with iOS background audio / microphone constraints. I’m exploring an app concept where: the user explicitly starts a temporary active session during that session, on-device wake-word / keyword detection runs locally no audio is stored or transmitted during passive monitoring monitoring stops when the user ends the session The intended UX is that the user may then lock the phone or place it away while the active session remains in progress. Question: Is there any App Store-compliant architecture that would allow local keyword / wake-word detection to continue while the device is locked or the app is backgrounded during that active session? Or would iOS lifecycle / background execution rules make this infeasible for custom wake-word detection? Interested in practical experience around: AVAudioSession background audio modes on-device speech processing App Review acceptability Thanks in advance.
Replies
0
Boosts
0
Views
297
Activity
2w
Background Location Tracking Not Reliably Relaunching App After Termination
We are developing a mileage tracking application that depends on continuous background location updates on iOS. Our app has the required background modes enabled: <key>UIBackgroundModes</key> <array> <string>remote-notification</string> <string>processing</string> <string>fetch</string> <string>location</string> </array> We are observing inconsistent behavior with background location tracking in app terminated state. In some cases, after a period of time, location updates stop completely. Sometimes iOS successfully relaunches the app when movement is detected and location updates resume correctly. However, in other cases, the app is not relaunched by the system, and we stop receiving location updates entirely. We reviewed Apple’s documentation on handling background location updates: https://developer.apple.com/documentation/corelocation/handling-location-updates-in-the-background Based on our observations, we would appreciate clarification on the following points: Is this considered expected iOS behavior or a system limitation? Under what conditions does iOS decide not to relaunch a terminated app for location events? Are there recommended best practices to improve the reliability of background location relaunch behavior? Is there any logging, diagnostics, or debugging mechanism available to determine why the app was not relaunched? Apple’s documentation mentions that location updates may be queued while the app is terminated and later delivered after relaunch. However, in some scenarios we do not receive those queued updates after the app restarts. Under what conditions can queued location updates be discarded or not delivered? Additional notes: We are using standard Core Location background updates. “Always” location permission is granted. Background App Refresh is enabled. The issue is observed intermittently across multiple iOS devices.
Replies
4
Boosts
0
Views
236
Activity
1d
Seeking Apple Recommended Solution for Extended, Deterministic Background Sync/Upload for Offline-First App (Large Data)
Context Our enterprise application is offline-first for iOS and iPadOS, designed to work completely offline, storing a very large local database (DB) and many attached files (images and videos) locally. Users create and update entities on the device.1 When connectivity is available, the app performs a bidirectional sync: local changes (including multi-gigabyte files) are uploaded, and thousands of DB updates are pulled down and applied locally. The Challenge: Foreground Requirement The complete sync process often requires 10 to 20 minutes to finish. Users expect their devices to proactively sync when online, even if it takes this long. Our fundamental problem is that, at present, users must keep the app in the foreground to complete the task. We have confirmed that on iOS, the system aggressively terminates the app process, typically after 30 seconds of being sent to the background. We currently advise users with large projects to keep the app in the foreground and connected to power.2 Existing Mitigation and Technical Details We have implemented several best practices to optimize transfers and manage device resources: We use battery checks before initiating large transfers, with a low battery threshold (around 15%) to pause actions if the device will enter a danger zone.2 Our upload mechanism uses HTTP Range Requests to implement a resumable single-stream approach for maximum throughput, ensuring that if a connection drops mid-transfer (even at 1.2 GB of a 2.5 GB file), we only re-transfer the remaining bytes, rather than losing all progress. This addresses network resilience and speed but not the OS background limitation.3 The Core Issue The various background options provided by iOS and iPadOS do not appear deterministic enough to reliably handle the immediate, extended data synchronization (uploading GB files and pulling down substantial DB changes) that we require. We are seeking a solution where a user-initiated task engages in background work almost immediately, reliably continuing for 10–20+ minutes after the user leaves the app or locks the screen, allowing for more "natural" device usage. Our Question for Apple Engineering Given the high volume of data transfer and the need for deterministic, extended background execution, what is Apple's current recommended, official approach for an enterprise app that requires prolonged background syncs—specifically, how can we architect this on iOS/iPadOS to reliably continue the upload and download of large data sets and database updates after the app moves out of the foreground?
Replies
2
Boosts
0
Views
70
Activity
4d
Sleep onset detection on watchOS: viable non-workout paths and CMSensorRecorder behavior
I'm building a sleep tracker for couples — the headline feature is a notification to your partner the moment you fall asleep (and another when you wake up), detected on the Apple Watch from accelerometer and heart-rate data. The detection has to happen within minutes of onset for the product to make sense. My setup HKObserverQuery on heart rate with enableBackgroundDelivery(.immediate), re-registered on foreground. WKApplicationRefreshBackgroundTask rescheduled every 15 minutes. CMSensorRecorder.recordAccelerometer(forDuration: 12 * 3600) re-armed on every wake. A van Hees-style stillness classifier reading the last ~35 minutes of the buffer, with heart rate as a soft confirmer. HealthKit and Motion & Fitness authorized on both iPhone and watch. The observer's completionHandler() is called on every branch and the handler stays well under the 15-second watchdog. No HKWorkoutSession as my app is not a workout. Questions Is CMSensorRecorder paused or deprioritized while the Apple Watch's automatic sleep detection has classified the user as asleep? On a worn watch with the recorder armed for 12 hours, accelerometerData(from:to:) over a 35-minute window inside the auto-detected sleep period returns zero samples. The exact same call an hour later, once the watch has decided the user is awake, returns roughly ten thousand samples for an equivalent window. The user never activated Sleep Focus or Theater Mode — the only sleep-related state at play is the watch's own automatic detection, the same one that writes Core / REM / Deep stages into Apple Health. Is this documented power management I missed, or is it unexpected? Happy to file Feedback with a sysdiagnose during the window if you confirm it shouldn't behave this way. Is there a sanctioned non-workout path on current watchOS for detecting sleep onset within a few minutes of it happening? A full night recently produced a five-hour stretch with zero observer callbacks and zero background-refresh deliveries between bedtime and wake. The historical guidance to third-party sleep apps has been to reconstruct nights post-hoc from sleepAnalysis samples rather than attempt live detection. Is that still the recommendation today, or is there an API I've missed that would give an onset-focused app tighter wakes around bedtime? What is the current App Store review stance on HKWorkoutSession for sleep tracking? Would an app that auto-starts a .other / indoor workout only when its own classifier detects pre-sleep signals at the user's typical bedtime, ends the session as soon as onset is confirmed, never starts one outside that gated condition, and explicitly discloses "sleep tracking via workout session" in the App Store metadata — be an acceptable pattern, or grounds for rejection regardless of disclosure?
Replies
1
Boosts
0
Views
72
Activity
2d
Background Termination Investigation
Hello, We are currently investigating an issue where our app is being terminated by the system while running in the background. At the moment, the app does not perform any significant background activity, and memory usage remains relatively low (approximately 150–200 MB). Despite this, the app is still being terminated in the background, even under conditions where other apps appear to remain active. From our investigation so far, the issue does not appear to be related to: High memory consumption Explicit background task misuse Application crashes on our side For additional context, we had previously used silent push notifications to trigger heavy upload operations in the background. Since we suspected this behavior might be contributing to the issue, we completely stopped using this mechanism approximately two weeks ago. However, the background terminations are still occurring. We would like to better understand the possible causes of this behavior. Specifically, could this be related to: Watchdog terminations Background assertion or lifecycle violations RunningBoard resource management Jetsam policies Background execution timeouts Any other system-level resource or process management constraints We would greatly appreciate any guidance on how to identify the root cause or which logs/diagnostics we should focus on to further investigate the issue. Thank you.
Replies
2
Boosts
0
Views
126
Activity
1d