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

134 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Background Tasks Resources
General: DevForums tag: Background Tasks Background Tasks framework documentation UIApplication background tasks documentation ProcessInfo expiring activity documentation watchOS background execution documentation WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it! WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI iOS Background Execution Limits DevForums post UIApplication Background Task Notes DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.3k
Jun ’22
Two functions of centralManager used
I am trying to code out a background refresh part of my app but there are two centralManager functions in the app. func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { if peripheral.identifier.uuidString == selected { selectedPeripheral = peripheral centralManager?.stopScan() centralManager?.connect(selectedPeripheral!, options: nil) } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("Connected to peripheral: \(peripheral)") // Subscribe to disconnection events peripheral .publisher(for: \.state) .sink { [weak self] state in if state == .connected { self?.isConnected = true } else if state == .disconnected { // Peripheral is disconnected, send notification if self?.isConnected == true { self?.sendNotification() self?.isConnected = false } } } .store(in: &cancellables) } and this is the refresh part private func handleBluetoothMonitoring(task: BGAppRefreshTask, bluetoothMonitor: BluetoothMonitor) { let queue = DispatchQueue(label: "com.yourcompany.bluetoothmonitor") task.expirationHandler = { // Handle expiration of the task if needed } queue.async { // Perform Bluetooth monitoring tasks here if let centralManagerInstance = bluetoothMonitor.centralManager { DispatchQueue.main.async { bluetoothMonitor.centralManagerDidUpdateState(centralManagerInstance) } } else { print("Central manager is nil") } // End the task task.setTaskCompleted(success: true) } } Is there a way to solve this? Thanks!
1
0
68
5d
Getting 561015905 while trying to initiate recording when the app is in background
I'm trying to start and stop recording when my app is in background periodically. I implemented it using Timer and DispatchQueue. However whenever I am trying to initiate the recording I get this error. This issue does not exist in foreground. Here is the current state of my app and configuration. I have added "Background Modes" capability in the Signing & Capability and I also checked Audio and Self Care. Here is my Info.plist: <plist version="1.0"> <dict> <key>UIBackgroundModes</key> <array> <string>audio</string> </array> <key>WKBackgroundModes</key> <array> <string>self-care</string> </array> </dict> </plist> I also used the AVAudioSession with .record category and activated it. Here is the code snippet: func startPeriodicMonitoring() { let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSession.Category.record, mode: .default, options: [.mixWithOthers]) try session.setActive(true, options: []) print("Session Activated") print(session) // Start recording. measurementTimer = Timer.scheduledTimer(withTimeInterval: measurementInterval, repeats: true) { _ in self.startMonitoring() DispatchQueue.main.asyncAfter(deadline: .now() + self.recordingDuration) { self.stopMonitoring() } } measurementTimer?.fire() // Start immediately } catch let error { print("Unable to set up the audio session: \(error.localizedDescription)") } } Any thoughts on this? I have tried most of the ways but the issue is still there.
3
0
141
1w
Background NSURLSession when uploads must be prompt
I have an app with which users take photos and upload them in batches. It's used often on older devices, in areas with less than ideal network, and for durations of a full workday - so often the device has low power. The current implementation of uploads uses an NSURLSession configured for the foreground, and as a result my users are used to having to keep the app in the foreground while an upload completes. However, these uploads are big and connectivity is often low, so this takes a long time - often users are stuck waiting with the app foregrounded for 15 minutes or so while the upload completes. So, I created a build which uses an NSURLSession configured for the background. In the ideal case, users could start the upload, put the device in their pocket and continue their workday, and the next time they open their device it will be complete. For some users this ideal case has come true. However, for others, the uploads sit in progress for an indeterminate amount of time, making no progress. My suspicion is that this is because the OS is deferring them until a time when network and power is more available. However, my users are using work devices at a work location - reliable power and network might never be available. Being able to background the app and continue working is valuable for these users, but having the upload complete promptly is essential for them. My questions are: Is it true that background configured NSURLSessions will defer network requests when connectivity or power is low, even if discretionary = NO? Is the exact behavior for when requests will be attempted in the background documented? Is there a way to reliably test background configured NSURLSessions in XCode? I've attempted throttling my connection with Charles Proxy, and using my device in Low Power Mode, but I'm unable to reproduce the request stalling behavior my users are experiencing in the wild. Is there a way to create an NSURLSession that will muscle through difficult or inefficient uploads in the background, with the same reliability as a foreground session? If not, what is Apple's recommended approach to situations like mine? I've considered queueing both a background and foreground upload, and cancelling the other once one completes, but this seems disrespectful to the user's resources. Will setting timeoutIntervalForResource to a lower value cause the OS to more aggressively attempt uploads? Or simply to throw an error sooner? I want the OS to give the upload a long time to complete, but I also want it to attempt it right away. Thanks for any information!
1
0
140
1w
Increase in app crashes on iOS 17.4
We have an iOS app built using Capacitor. We are seeing a large increase in app crashes on iOS 17.4 (iPhone). Other OS versions seem to be showing significantly fewer crash numbers. We are unsure what is causing this, as our app did not go through any major releases. I have attached the crash log below. Thanks Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: RUNNINGBOARD 0xd00d2bad
5
0
269
3d
App Logo Above Watch Face on Apple Watch
I am running two different background modes(not at the same time), 1 with a workout and 1 with a location. I noticed that the app logo appears above the watch face for both background modes but does not show up consistently. I wonder what the significance of the logo showing up above watch face is? Additionally why does it show up sometimes but not others? Thanks
0
0
135
2w
Discover and connect to BLE peripherals more rapidly in background
We are developing an app which connects to a BLE peripheral in the background whenever it gets close to it. What we have used so far is that we monitor a circular region. When the phone enters the region the app will start scanning for peripherals and when it discovers the peripheral it connects to it. This worked pretty well for the last few iOS versions, perhaps iOS 14-16. It wasn't perfect but for the most part it would feel like it connected rather quickly when you would approach the BLE peripheral. If you listen to music via BLE or talk to someone using your BLE headset then it could sometimes work noticeably worse. But, as said, for the most part it would work satisfactory. Starting with iOS 17 and analyzing the functionality over the past 6 months or so we've noticed a clear worsening of it. It does generally connect to the peripheral but the user might often have to wait for quite some time. Rather frequently the user must even light up the screen of the phone before anything even happens. It appears that some sort of resource allocation, battery saving feature or similar has affected this functionality greatly. The time difference between entering a region and physically approaching the device is generally around 2-3 minutes. We have tried to do it more in line with documentation and follow the guidelines that we find in: https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html So in doing this we do not start scanning for peripherals when a region is entered, but instead we directly invoke connectPeripheral:options:. This way we offload to the system that we want to connect to that peripheral. However, when testing this we see no real improvement. Sometimes it connects satisfactorily. Sometimes it doesn't really connect at all. Many times it connects if the user lights up the screen. So just looking at what the user is experiencing our analysis is that doing it this way works even worse than what we previously did. I understand that the system has many resources to consider and that some may have to wait while others perform things. But are there any documentation on what one could expect from initiating a connectPeripheral:options: from the background? In the link I posted it simply states the iOS device will reconnect when the user returns home. So not much detail in terms of performance which is crucial for our application. If there aren't any further details on the performance, are there any other ways to improve this functionality? We are not looking at draining the battery whatsoever but we simply need our background running app to be as responsive as possible for a few minutes after it has been launched by the region monitoring. We understand that battery life is important but since this happens rarely and sparsely (not more than a few times per day) it seems reasonable that there should be a way to be able to make it function properly.
2
0
177
2w
Background AVExportSession for UHD Videos
First off - I have read and fully understand this post - Apple doesn't want us abusing users' hardware so as to maximize the quality of experience across apps for their customers. I am 100% on board with this philosophy, I understand all design decisions and agree with them. To the problem: I have an app that takes photo assets, processes them for network (exportSession.shouldOptimizeForNetworkUse = true), and then uploads them. Some users have been having trouble, did some digging, they're trying to upload 4K 60FPS videos. I think that is ridiculous, but it's not my place. The issue is that the export time for a 4K60FPS video that is ~40s long can be as long as 2m. So if they select a video to upload, and then background the app that upload will ALWAYS fail because the processing fails (I have BG uploads working just fine). My understanding is that default I have 30s to run things in the background. I can use UIApplication.pleasegivemebackgroundtime to request up to 30 more seconds. That is obviously not enough. So my second option is BGProcessingTask - but that's not guaranteed to run ever. Which I understand and agree with, but when the user selects a video while the app is in the foreground the expectation is that it immediately begins processing. So I can't use a BGProcessingTask? Just wondering what the expected resolution here is. I run tasks, beg for time, if it doesn't complete I queue up a BGTask that may or may not ever run? That seems ****** for a user - they start the process, see it begin, but then if the video is too big they just have to deal with it possibly just not happening until later? They open up the app and the progress bar has magically regressed. That would infuriate me. Is there another option I'm not seeing? Some way to say "this is a large background task that will ideally take 30-60s, but it may take up to ~5-7m. It is user-facing though so it must start right away"? (I have never seen 5-7m, but 1-2m is common) Another option is to just upload the full 4K60FPS behemoth and do the processing on my end, but that seems worse for the user? We're gobbling upload bandwidth for something we're going to downsample anyway. Seems worse to waste data than battery (since that's the tradeoff at the end of the day). Anyway, just wondering what the right way to do this is. Trivially reproducible - record 1m 4K60FPS video, create an export session, export, background, enjoy failure.
2
0
155
2w
Background Modes not working with TestFlight Build
So, we've got a mobile app that is using background processing to occasionally scan for nearby BLE beacons. When running a debug / local build of the app, everything behaves as expected, but if we upload a build to TestFlight and install from there, the background processing doesn't happen. This behavior would seem to point to a capability in the App ID not being provisioned, but when I look in the Identifiers section of Apple Developer, Background Modes as a capability isn't listed for either the existing Application Identifier or when creating a brand new one. The app has the Background Modes capability assigned if I look at it in XCode. Any thoughts as to where to look next or what I'm missing?
2
0
239
3w
Battery Consumption
We are developed app based on driver behaviour using location and sensor data. It's working in both background and foreground using region monitoring. Its consume more battery comparing other apps like. Its reduce 5% for every 5 to 10 mins of duration. We are using for our app functionality Location (Always) - every 1sec Sensor - Accelerometer - every 20data for 1sec Background - Region monitoring Time Action - 1sec for 20time Any possible way to reduce battery consuming? If any please suggest your points. Thanks in advance for your comments.
0
0
121
3w
HealthKit Background execution
Hi All, I have a strange issue. I am using enableBackgroundDelivery for updating user step count in background mode using health kit. It works fine when I execute the app by pressing 'Run' in xcode. But the code is not triggering when I am directly launching it on my device. I have tried many different things but cannot figure out the issue from 2 days 😭. I would really appreciate any suggestions. Thanks
1
0
187
4w
watchOS: Resume recording from AudioInterruption in background mode
Hi, I have a watchOS app that records audio for an extended period of time and because the mic is active, continues to record in background mode when the watch face is off. However, when a call comes in or Siri is activated, recording stops because of an audio interruption. Here is my code for setting up the session: private func setupAudioSession() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default, options: [.overrideMutedMicrophoneInterruption]) try audioSession.setActive(true, options: .notifyOthersOnDeactivation) } catch { print("Audio Session error: \(error)") } } Before this I register an interruption handler that holds a reference to my AudioEngine (which I start and stop each time recording is activated by the user): _audioInterruptionHandler = AudioInterruptionHandler(audioEngine: _audioEngine) And here is how this class implements recovery: fileprivate class AudioInterruptionHandler { private let _audioEngine: AVAudioEngine public init(audioEngine: AVAudioEngine) { _audioEngine = audioEngine // Listen to interrupt notifications NotificationCenter.default.addObserver(self, selector: #selector(handleAudioInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil) } @objc private func handleAudioInterruption(notification: Notification) { guard let userInfo = notification.userInfo, let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else { return } switch interruptionType { case .began: print("[AudioInterruptionHandler] Interruption began") case .ended: print("[AudioInterruptionHandler] Interruption ended") print("Interruption ended") do { try AVAudioSession.sharedInstance().setActive(true) } catch { print("[AudioInterruptionHandler] Error resuming audio session: \(error.localizedDescription)") } default: print("[AudioInterruptionHandler] Unknown interruption: \(interruptionType.rawValue)") } } } Unfortunately, it fails with: Error resuming audio session: Session activation failed Is this even possible to do on watchOS? This code worked for me on iOS. Thank you, -- B.
2
0
327
Apr ’24
How to keep a socket server in an iOS app alive when app goes to background or suspended?
Hi all, My application requires to create a WebSocket server on an iOS application for other devices can connect and transfer data with my application. I used Vapor library to create a socket server and it works well when the application is in the foreground. I am trying to keep the server alive when my app moves to the background or the suspended state so that my app and other devices can continue to communicate with each other. Is there any ways to achieve that? I tried to turn on a mode: "Audio, Airplay, and Picture in Picture" in background modes section in Signing &amp; Capabilities and then my application can still communicate with clients when it is background mode. But my application is an application for user can edit image and send it to other devices through sockets and it does not have audio, airplay,.. feature. Is it ok to publish the app to the app store in the future? Thank you!
2
0
352
Apr ’24
Maintaining MQTT connection in background
Hello, I have an app that receives critical alarms. This is usually done through remote push notifications from the server, but to add redundancy I'd like to add a MQTT connection as well. There are scenarios where internet connection might be missing (but there is a local WiFi connection to the server) hence I'd like to deliver the alarms directly from server to client without going out via the Internet. The problem is that according to all restrictions on iOS, the MQTT connection will not be maintained in the background and disconnect occurs within 20-30 sec after going in the background and shutting the screen. I'm aware of all the background modes that iOS allows but none fall within this scenario. Is there a way to maintain a MQTT connection (or some other type of network connection) in the background on iOS?
1
0
325
Apr ’24
AudioSession activation while App is in background or killed
Hello, I'm developing a voice communication App using Livekit SDK. Everything works fine in the foreground, AudioSession is activated and audio transmitted. However, I would like to add a feature, I would like my app to receive audio even when it's in background or terminated. I know I can run code when the App is in that state by sending a background push notification, but the only thing that is not working in that case is the AudioSession activation. It fails with error "Session activation failed", no more clues. I tried every combination of category and mode, but no success. Bacground modes in XCode have been activated: -Audio, AirPlay, and Picture in Picture -Background Processing Is this a limit of Livekit? I would be grateful if someone can point me into the right direction.
0
0
291
Apr ’24
BGTask running while iPad is awake--how is this possible?
We have been using the BGTask (specifically a BGProcessingTask) reliably for the last couple of years for our app. Up until now they wake up automatically while the screen is off, the iPad is plugged in, and the app is running (that is, in the background), but never while the screen is on (that is, never when the scenePhase == .active). For the last month or so, I've noticed that they are triggering now while the screen is displayed. How is this possible??? Did something change with a recent version of iOS? It's violating Apple's own documentation, which describes the BGProcessingTask as: "A time-consuming processing task that runs while the app is in the background."
2
0
375
Mar ’24
How to run a background task on keyboard extension to communicate with a MFi device?
I'm working on a app that can communicate, send and receive data from our own MFi scanner. Ideally, this app can receives data and remains communication even when it's in background, but I can only runs a background task for maximum 30 sec. Along with this main app, we also have a keyboard extension as an interface that can publish collected data to other app that user prefers with string format. However, It seems like Apple doesn't allow to implement UIApplication.shared.beginBackgroundTask method in extension class, is there any alternative that worth to try? Also, can I extend app background task time elapsed to at least 30 minutes? If I can get an official response would be great!
1
0
405
Mar ’24
Error: _SwiftData_SwiftUI: one-time initialization function for empty
My App keeps crashing in the background and I don't know why. I'm using SwiftData and SwiftUI. I'm setting up a .backgroundTask like this: import SwiftUI import SwiftData import TipKit @main struct MyAppName: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @State var navManager = NavigationManager.load() @State var alerter: Alerter = Alerter() var sharedModelContainer: ModelContainer = { do { return try ModelContainer(for: DataController.schema, configurations: [DataController.modelConfig]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { SetupView() .accentColor(.myAccentColor) .environment(alerter) .alert(isPresented: $alerter.isShowingAlert) { alerter.alert ?? Alert(title: Text(verbatim: "")) } .task { try? Tips.configure([ .displayFrequency(.immediate), .datastoreLocation(.applicationDefault) ]) } .onAppear { setUpAppDelegate() } } .modelContainer(sharedModelContainer) .backgroundTask(.appRefresh(Const.backgroundAppRefreshId)) { @MainActor in let container = sharedModelContainer await RefreshManager.handleBackgroundVideoRefresh(container) } .environment(navManager) } func setUpAppDelegate() { appDelegate.navManager = navManager } } The RefreshManager.handleBackgroundRefresh(...) goes on to load data and then insert models for them via SwiftData. It only happens occasionally and afaik only in the background. Weirdly enough the issue seems to be there even when I only print something in the background task. Even when I don't schedule/set a background task at all. How can that be? The crashes started in the version that included the .backgroundTask, although perhaps it's related to something else. I'm still trying to further narrow it down. This is the crash report that I'm getting: Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001a1bb98c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [809] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a1bb98c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 libswiftCore.dylib 0x00000001a1c27d14 swift_unexpectedError + 664 (ErrorType.swift:188) 2 _SwiftData_SwiftUI 0x000000024310cd78 one-time initialization function for empty + 300 (ModelContainer+Extensions.swift:5) 3 libdispatch.dylib 0x00000001ab16add4 _dispatch_client_callout + 20 (object.m:576) 4 libdispatch.dylib 0x00000001ab16c654 _dispatch_once_callout + 32 (once.c:52) 5 _SwiftData_SwiftUI 0x000000024310cdf8 one-time initialization function for empty + 124 (ModelContainer+Extensions.swift:12) 6 libdispatch.dylib 0x00000001ab16add4 _dispatch_client_callout + 20 (object.m:576) 7 libdispatch.dylib 0x00000001ab16c654 _dispatch_once_callout + 32 (once.c:52) 8 _SwiftData_SwiftUI 0x0000000243122170 key path getter for EnvironmentValues.modelContext : EnvironmentValues + 140 (<compiler-generated>:0) 9 libswiftCore.dylib 0x00000001a1ce4628 RawKeyPathComponent._projectReadOnly<A, B, C>(_:to:endingWith:) + 1012 (KeyPath.swift:1701) 10 libswiftCore.dylib 0x00000001a1ce3ddc KeyPath._projectReadOnly(from:) + 1036 (KeyPath.swift:331) 11 libswiftCore.dylib 0x00000001a1ce8348 swift_getAtKeyPath + 24 (KeyPath.swift:2029) 12 SwiftUI 0x00000001a7af4814 EnvironmentBox.update(property:phase:) + 872 (Environment.swift:273) 13 SwiftUI 0x00000001a782a074 static BoxVTable.update(ptr:property:phase:) + 396 (DynamicPropertyBuffer.swift:294) 14 SwiftUI 0x00000001a78297b0 _DynamicPropertyBuffer.update(container:phase:) + 104 (DynamicPropertyBuffer.swift:215) 15 SwiftUI 0x00000001a887fb78 closure #1 in closure #1 in DynamicBody.updateValue() + 104 (DynamicProperty.swift:447) 16 SwiftUI 0x00000001a887fbb8 partial apply for closure #1 in closure #1 in DynamicBody.updateValue() + 28 (<compiler-generated>:0) 17 libswiftCore.dylib 0x00000001a1bcc068 withUnsafeMutablePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:82) 18 SwiftUI 0x00000001a887f9dc closure #1 in DynamicBody.updateValue() + 408 (DynamicProperty.swift:446) 19 SwiftUI 0x00000001a887f5c0 DynamicBody.updateValue() + 712 (DynamicProperty.swift:445) 20 SwiftUI 0x00000001a71e8bf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 21 AttributeGraph 0x00000001cbd4c240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 22 AttributeGraph 0x00000001cbd42f38 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 (ag-graph-update.cc:719) 23 AttributeGraph 0x00000001cbd42810 AG::Graph::input_value_ref_slow(AG::data::ptr<AG::Node>, AG::AttributeID, unsigned int, unsigned int, AGSwiftMetadata const*, unsigned char&, long) + 720 (ag-graph.cc:1429) 24 AttributeGraph 0x00000001cbd423a4 AGGraphGetValue + 228 (AGGraph.mm:701) 25 SwiftUI 0x00000001a887f548 DynamicBody.updateValue() + 592 (DynamicProperty.swift:444) 26 SwiftUI 0x00000001a71e8bf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 27 AttributeGraph 0x00000001cbd4c240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 28 AttributeGraph 0x00000001cbd42f38 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 (ag-graph-update.cc:719) [...] 107 SwiftUI 0x00000001a7cf79fc static App.main() + 132 (App.swift:114) 108 MyAppName 0x0000000100e6d120 static MyAppNameApp.$main() + 52 (MyAppNameApp.swift:0) 109 MyAppName 0x0000000100e6d120 main + 64 110 dyld 0x00000001c67c2d84 start + 2240 (dyldMain.cpp:1298) The report also says key path getter for EnvironmentValues.modelContext, which seems odd. Any idea where I could start to look for the issue? I'm currently just trying things out, pushing them to TestFlight and waiting for crashes to happen. As soon as I can narrow it down further I'll update this.
6
1
558
Apr ’24