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

131 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.4k
Jun ’22
Background Mode for BLE app
We have a BLE app and we are trying to get it to work in Background Mode consistently. Use case: RFID BLE reader is attached to a printer Person installs the iOS app on phone and enables Background Mode Person walks to the printer with phone iOS App connects to RFID BLE reader and authenticates to allow secure printing Current status/Problem: On several tests, we were able to connect to the BLE device, but with inconsistent results. For example, for 5 - 2 min tests - (1) we see 8 successful scans, (2) 1 successful scan, (3) 20 successful scans, (4) 15 successful scans, and (5) 11 successful scans. In the above tests, we were getting a scan every 3-4 secs and then it scanning stops. The objective is to maintain continuous scanning until user closes app or disables background mode. Why does scanning stop? How can we make scanning continuous? Any guidance you can provide is appreciated.
2
0
102
6h
Live Activity Widget -
Hi, I'm developing a Live Activity Widget that shows a count down timer. In the current solution I have a stop watch that is responsible for handling the start, stop, resume, reset function. When the stop watch starts I have timer that calls on an updateTime function every 0.2 seconds. This works well. The problems comes when I try to use my stop watch in the Live Activity Widget. I have a timer that updates the live activity attributes with content every 0.5 second. // Start the activity let activity = try? Activity.request(... DispatchQueue.main.async { self.logger.log("Start internal timer") self.timer = Timer.scheduledTimer(withTimeInterval:0.5, repeats: true) { _ in self.logger.log("Update activity widget.") self.updateActivity() } } Is this a correct approach? If not what should I use to implement a stop watch with a count down timer and a corresponding progress bar/view?
0
0
58
3d
Periodic background location polling for infrequently used app
My team and I would like to develop a mechanism that collects the user’s location a few times per day, to detect when the user travels to a different country, for the user’s convenience. The app is very likely going to be opened very rarely. The user would of course be made aware of why collecting the location a few times a day is desired - namely, saving them the effort of having to remember to open the app every time they travel. My question is the following: given that the app would rarely be interacted with, what is the best strategy for collecting the location? The goal is to handle scenarios where the OS might avoid sending location events or notifications to the app. I imagine that the backend might need to intervene and send the occasional push notification to remind the user to open the app from time to time. There are 3 strategies that I’m aware of: LocationManager’s startMonitoringSignificantLocationChanges Scheduling BGAppRefreshTasks Using silent push notifications scheduled by the server. Ideally, using a location push service extension Keeping in mind the “Background execution demystified” WWDC session, documentation, and other threads, I concluded the following: The first idea is probably the least suitable, since it probably requires the app to be opened often, and the location updates would not be sent by OS if the app has been terminated from the app switcher. The second approach would also suffer from infrequent use and termination. The third approach seems not to be affected as much by infrequent usage. I understand that the 3rd strategy might also lead to the OS omitting to wake up the app when it has been terminated by the user. How would you implement this mechanism?
1
0
160
1w
Network Call (Rest API) Fails During iOS Background Task Execution
Issue Statement: I am encountering difficulties with executing network calls from within a Flutter method during iOS native background task handling. Background: In my iOS Flutter application, I've implemented background task handling using native iOS code (Swift), leveraging the BGTaskScheduler's BGProcessingTask provided by iOS. The background task is set up to perform periodic network requests, but the network calls are made through a Flutter method invoked via platform channels from the iOS code. Problem Description: While the background task executes as expected and invokes the Flutter method successfully, the network calls initiated within the Flutter method fail to complete during background task execution. The method execution seems to proceed up to the point of initiating the network call, but the call itself does not complete successfully.
1
0
109
1w
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
143
3w
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
209
3w
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
203
4w
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
410
2w
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
190
May ’24
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
248
May ’24
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
212
May ’24
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
331
May ’24
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
184
May ’24
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
273
Apr ’24
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
365
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
421
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
384
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
342
Apr ’24