Background Tasks

RSS for tag

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

Background Tasks Documentation

Pinned Posts

Posts under Background Tasks tag

140 Posts
Sort by:
Post not yet marked as solved
2 Replies
1.5k Views
When my app enter to background, I start a background task, and when Expiration happens, I end my background task. The code likes below: backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (backgroundTask != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; backgroundTask = UIBackgroundTaskInvalid; [self cancel]; } }); }]; When the breakpoint is triggered at the endBackgroundTask line, I also get the following log: [BackgroundTask] Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x282d7ab40>: taskID = 36, taskName = Called by MyApp, from MyMethod, creationTime = 892832 (elapsed = 26). This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this. The log don't appear every time, so why is that? Is there something wrong with my code?
Posted
by
Post not yet marked as solved
5 Replies
916 Views
Hi, I'd like to develop an iOS application that keeps the mic open for voice recording and processing even when the screen is off. I want to perform speech-to-text requests whenever samples of voice are detected (using a voice activity detection library) and also send requests to the cloud based on what is spoken. I've enabled the Audio background mode and preliminary testing seems to indicate that this is working. That is, I can press "record" in my app, switch to another app then shut the screen off, and speak for several seconds before auto-stopping the recording and sending it to a SFSpeechRecognizer task, which appears to succeed. However, I have read that this should not be supported so before going further down this path, I wanted to understand what exactly are the processing limitations in this mode? The documentation doesn't seem very clear to me. Thanks, -- B.
Posted
by
Post not yet marked as solved
1 Replies
672 Views
We have a SwiftUI watch app that has the workout processing background mode. Every time our users raise their wrist the app opens. I understand that this is one of the abilities granted by Apple with the given background mode for active workouts. I wonder if there is a way for us to programmatically turn off this ability, given that this also drains the users battery. Thanks
Posted
by
Post not yet marked as solved
0 Replies
330 Views
The programming guide for Core Bluetooth states that "Upon being woken up, an app has around 10 seconds to complete a task. Ideally, it should complete the task as fast as possible and allow itself to be suspended again. Apps that spend too much time executing in the background can be throttled back by the system or killed." My use case however demands that I continue to receive live data from a Bluetooth peripheral for more than 10 seconds. In my testing things are working fine and my app runs for more than 10 seconds. Why is this the case and could this become an issue later on? I have set the background modes for Background Processing, Fetch and Use Bluetooth LE accessories.
Posted
by
Post not yet marked as solved
0 Replies
646 Views
I have an idea for an iOS App that involves creating alarms and "undismissable" notifications. Currently, iOS has multiple system features like silent/ring mode, focus mode, security protections, and other system features that would limit the functionality of an app with this purpose. Basically, think of a system Amber Alert or how the iOS Alarm app works. Regardless of these system settings, the user will be notified of the importance of the alarm immediately. What I'm trying to develop are really two separate things. First an alarm app without a snooze (or a set snooze limit) where you must prove that you're awake. Second, integrate a web API service for volunteer first responders that notify them to respond to an emergency via an iOS app. These are not features that would limit a user's privacy, their experience using iOS, and, quite frankly, be something that is so difficult to implement. If anyone can direct me to any system APIs that would be available to use for the start of this app or make me aware of any "blockers" that would absolutely prevent me from developing this in iOS, I would really appreciate it. My research has not been very in depth and there are differences in opinions on approaches and possibilities. If you are an engineer at Apple and this turns out to be impossible or impractical with current versions of iOS, it would be great to have the ability to be able to do something of this nature in the future.
Posted
by
Post marked as solved
2 Replies
490 Views
I'm attempting to regularly interact with ApplicationMusicPlayer in MusicKit, even while in the background. I'd like to allow for changes in the network to allow me to change songs. While this works fine while the application is in the foreground, due to idiosyncrasies with how ApplicationMusicPlayer does not in fact "count" for your application actively playing audio while in the background my network connection becomes lost. I would like to check the network again while the app is in the background, and it seems like I could do so with BGAppRefreshTask. However, the frequency that I'd like to request would be on the order of sub-30s refresh timelines. This seems...excessive, given how BGAppRefreshTask seems to be documented. Are there best practices in terms of what is an appropriate interval for BGAppRefreshTask being executed? Is there an upper or lower bound on intervals that is known? Should I consider using something different to achieve what I'm after? Thanks for any help.
Posted
by
Post not yet marked as solved
0 Replies
392 Views
We guide our users to perform specific actions within our service using a timer, similar to interval training. Even when the user enters the background, they should receive a TTS notification and the live activity screen should be updated upon timer completion. Additionally, the user should be able to transition to the next timer at a specific time, even if they don't perform an action (which also requires TTS and live activity updates). Currently, the only thing we can control is scheduling a notification in advance. To enable background TTS notifications and control of live activity, we are considering using background notifications. However, they are irregular and more unstable in battery optimization situations, so we're wondering if there's a way to implement the desired functionality on iOS.
Posted
by
Post not yet marked as solved
0 Replies
812 Views
I am working on the background mode of nearby interaction, from the WWDC 2022 video, my Apps have to do pairing, connect with third party device's BLE Afterward, I have to implement a method called triggerPairing ( peripheral: peripheral, encryptedCharacteristics: CBCharacteristics), to trigger pairing process. The document mention that Apps should NOT discover the nearby interaction GATT service, but the encrypted characteristic is belonged to this service. how can I pass the parameters into the triggerPairing function if the Apps does not discover the service? what parameter should I pass into the function? Does anyone help?
Posted
by
Post not yet marked as solved
2 Replies
865 Views
Hi, I've read over many of the helpful posts on background modes ([1], [2], and responses to my thread [3]) but am encountering something that doesn't quite line up with my understanding. Background My app is using Bluetooth background mode in order to receive data from a peripheral periodically and then perform a network request (eventually, this will involve two network requests, one of them being an upload of audio, which will be a much larger transfer of up to a couple hundred KB, possibly requiring m4a compression first). In background mode, all the Bluetooth messages (currently a small string) are received reliably. The app is woken up and from my understanding, given some time to run in the background. I perform a POST request using URLSession.shared.dataTask(with: request). Problem Encountered These often succeed but sporadically fail with a timeout in background mode and with the error message "connection was lost". Furthermore, nearly every request in background mode is associated with some sort of connection error that appears in the log. Given that many of the requests still succeed, I'm not sure what to make of these. I see a variety of different ones. For example: Case 1: 2023-05-23 16:33:49.428668-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_read_request_report [C1] Receive failed with error "Socket is not connected" 2023-05-23 16:33:49.429633-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_read_request_report [C1] Receive failed with error "Socket is not connected" 2023-05-23 16:33:49.431677-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_read_request_report [C1] Receive failed with error "Socket is not connected" 2023-05-23 16:33:49.440358-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.440528-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.440640-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.440784-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.441459-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.441684-0700 ChatGPT for Monocle[4775:1088487] [quic] quic_conn_send_frames_for_key_state_block_invoke [C1.1.1.1:2] [-0151a6eeef6cab8c6b53cceead6cada7cf118a4e] unable to request outbound data 2023-05-23 16:33:49.445598-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_endpoint_handler_add_write_request [C1.1.1.1 104.18.6.192:443 failed channel-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns)] Cannot send after flow table is released 2023-05-23 16:33:49.445773-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_write_request_report [C1] Send failed with error "Socket is not connected" 2023-05-23 16:33:49.446925-0700 ChatGPT for Monocle[4775:1088487] Connection 1: received failure notification 2023-05-23 16:33:49.447348-0700 ChatGPT for Monocle[4775:1088487] Connection 1: write error 1:57 2023-05-23 16:33:49.464436-0700 ChatGPT for Monocle[4775:1088487] [connection] nw_endpoint_handler_unregister_context [C1.1.1.1 104.18.6.192:443 failed channel-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns)] Cannot unregister after flow table is released 2023-05-23 16:33:49.464974-0700 ChatGPT for Monocle[4775:1088487] [] nw_endpoint_flow_fillout_data_transfer_snapshot copy_info() returned NULL Case 2: 2023-05-23 16:34:09.422783-0700 ChatGPT for Monocle[4775:1088784] [connection] nw_read_request_report [C3] Receive failed with error "Socket is not connected" 2023-05-23 16:34:09.423511-0700 ChatGPT for Monocle[4775:1088784] [connection] nw_read_request_report [C3] Receive failed with error "Socket is not connected" 2023-05-23 16:34:09.425478-0700 ChatGPT for Monocle[4775:1088784] [connection] nw_read_request_report [C3] Receive failed with error "Socket is not connected" 2023-05-23 16:34:09.434263-0700 ChatGPT for Monocle[4775:1088784] [quic] quic_conn_send_frames_for_key_state_block_invoke [C3.1.1.1:2] [-01809801f02b5c3795812501322b6f9d3c91236f] unable to request outbound data The code that is generating these requests is fairly straightforward: public func send(query: String, apiKey: String, model: String, completion: @escaping (String, ChatGPTError?) -&gt; Void) { let requestHeader = [ "Authorization": "Bearer \(apiKey)", "Content-Type": "application/json" ] _payload["model"] = model if var messages = _payload["messages"] as? [[String: String]] { messages.append([ "role": "user", "content": "\(query)" ]) _payload["messages"] = messages } let jsonPayload = try? JSONSerialization.data(withJSONObject: _payload) let url = URL(string: "https://api.openai.com/v1/chat/completions")! var request = URLRequest(url: url) request.httpMethod = "POST" request.allHTTPHeaderFields = requestHeader request.httpBody = jsonPayload _task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { DispatchQueue.main.async { completion("", ChatGPTError.networkRequestFailed(error: error)) } return } if let data = data { let (contentError, response) = self.extractContent(from: data) if let contentError = contentError { DispatchQueue.main.async { completion("", contentError) } } else if let response = response { DispatchQueue.main.async { completion(response, nil) } } return } DispatchQueue.main.async { completion("", ChatGPTError.responsePayloadParseError) } } _task?.resume() } Questions Is there any way to make this process more reliable? I assume the error messages are meaningful and should not be ignored. If not, will I end up encountering issues when trying to upload larger payloads? Thank you! -- B.
Posted
by
Post not yet marked as solved
1 Replies
447 Views
I have an App that is part of a VoIP PBX system but which is NOT a VoIP App. It acts like a remote control that allow you to forward calls to our VoIP PBX to your cellular phone, or even setup calls to internal extensions all by using the Cellular network. One of the features we want to implement is to indicate to other users on our VoIP PBX system that someone using our App is in an active call using the cellular network. We managed to make that work, but only whilst the App is in the foreground. We are now struggling to find proper ways to activate a little bit of code in our App that will relay the Phone App state (RINGING, OFFHOOK, INCALL, etc...) to our VoIP PBX system. We are not a VoIP application and as such cannot utilise CallKit, and from what I understand, we cannot use PushKit anymore without using CallKit because people were abusing it to keep running their App in the background and thus reducing battery life. (Which I fully comprehend). But our app does not need to be active in the background and isn't a VoIP App, we only need it to wake up when the Phone App state changes and then do it's small networking task. So, can this actually be done properly? PS: To ensure the privacy of the user, the user needs to enable this feature him/herself. It is not enabled by default and can be switched off by the user as well.
Posted
by
Post not yet marked as solved
0 Replies
267 Views
In my iOS app, I have a requirement to fetch files from one server and upload them to a different server in the background mode. The task should be performed at a preset frequency, such as every 5 minutes. However, it seems that the functionality is not working properly in my app. Can someone please clarify the possible reasons for this issue? Thank you!
Posted
by
Post not yet marked as solved
1 Replies
288 Views
In my iOS app, I have a requirement to fetch files from one server and upload them to a different server in the background mode. The task should be performed at a preset frequency, such as every 5 minutes. However, it seems that the functionality is not working properly in my app. Can someone please clarify the possible reasons for this issue?
Posted
by
Post not yet marked as solved
4 Replies
793 Views
I know ios apps have the following lifecycle. active background suspended not running inactive My question is if my app can be killed in background state in the lifecycle above? Especially, I'm using beginBackgroundTask(expirationHandler:) to extend background time before suspended. Then my app is terminated with the following message without expirationHandler being called. Message from debugger: Terminated due to signal 9 Does this potentially happen? Actually I'm runnning a heavy task that requires CPU usage in background state, so is this a cause of this problem?
Posted
by
Post not yet marked as solved
2 Replies
332 Views
Hi, I'm working on an app that uses an XMPP Frame Work. Right now i am using xmppStream.enableBackgroundingOnSocket = YES; ... till Xocde 15 it is working Fine. But when Xcode Upgrade to 16.0 the app is getting crashed and it is giving hint as xmppStream.enableBackgroundingOnSocket = YES; will not work from iOS OS 11.0 . The app stops working when the app goes into the background when i am using xmppStream.enableBackgroundingOnSocket = NO; Is there any way to keep this working in the background? Ideally we'd like to be able to receive an XMPP message and if the app is not in the foreground, we'd post a local notification. Thanks Mahesh
Posted
by
Post not yet marked as solved
0 Replies
425 Views
I'm trying to make use of the background tasks to prefetch content while the app is in background. It works fine for a single task. When multiple tasks are registered (for different refresh intervals), only the first one is getting triggered. Not sure what I'm missing. I have posted few code blocks from a sample app I'm trying to build. Following is the list of identifiers defined in Info.plist. <key>BGTaskSchedulerPermittedIdentifiers</key> <array> <string>com.mycompany.myapp.task.refresh3</string> <string>com.mycompany.myapp.task.refresh2</string> <string>com.mycompany.myapp.task.refresh1</string> </array> Below is basically how I'm trying to make it work. @objc func registerTasks() { registerTask(Self.backgroundTaskIdentifier1) registerTask(Self.backgroundTaskIdentifier2) registerTask(Self.backgroundTaskIdentifier3) } private func registerTask(_ identifier: String) { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) let isRegistered = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: queue) { task in self.refresh(identifier: identifier) task.setTaskCompleted(success: true) self.scheduleAppRefresh(identifier: identifier) } if isRegistered { scheduleAppRefresh(identifier: identifier) } } ` @objc func scheduleAppRefresh(identifier: String) { let request = BGAppRefreshTaskRequest(identifier: identifier) if identifier == Self.backgroundTaskIdentifier1 { let newDate = Date(timeIntervalSinceNow: 1 * 60 * 60) request.earliestBeginDate = newDate } else if identifier == Self.backgroundTaskIdentifier2 { let newDate = Date(timeIntervalSinceNow: 2 * 60 * 60) request.earliestBeginDate = newDate } else if identifier == Self.backgroundTaskIdentifier3 { let newDate = Date(timeIntervalSinceNow: 3 * 60 * 60) request.earliestBeginDate = newDate } do { try BGTaskScheduler.shared.submit(request) UserDefaultsmanager.shared.setTime(time: "refresh scheduled for: \(identifier)") } catch { UserDefaultsmanager.shared.setTime(time: "Couldn't schedule app refresh") } }
Posted
by
Post not yet marked as solved
2 Replies
781 Views
Sorry if this is a stupid question but I haven't been able to find any information on whether an app can request and receive weatherKit data - the weather - while in the background. My app (AirCompare) makes extensive use of background URL sessions to fetch and process weather data. If certain conditions are met, a notification alert is sent to the user so the user can decide whether to activate the app. For instance if rain is in the forecast, the app alerts the user that they might want to close their windows. Making the app active will execute HomeKit control and accomplish that. Will I be able to replace the background URL session with the appropriate code and be able to fetch weather data in the background?
Posted
by
Post not yet marked as solved
1 Replies
817 Views
Hello everyone, I’m developing an app using Flutter. Users can establish a websocket connection in order to receive order requests from the server. However, when I lock the screen, the socket connection disconnects. I have Background Process and Background Fetch enabled through Xcode. Is there a way to keep the app alive even if it is in background? I only need the websocket connection to stay alive. Thank you!
Posted
by
Post not yet marked as solved
6 Replies
1k Views
Hello everyone, this is my first question here. I am a mobile developer for a company that uses smartphones like iPhone/Android devices in order to perform automated tests about Network QoE for our customers. In our use case solutions needs to be full automated without human interactions, i read a lot about the fact that on iOS is not possibile in any "standard" way to perform launch of our app on iOS startup. I also read about "Single App Mode" to launch app on reboot but our app could offer features to launch other apps, so i feel that this way is not tailored on our needs. My question is: Does it exist a way to make our app launched on system reboot? On Android devices there is the opportunity to make app running as services and auto launch them via "Autostart option". I'm open to every idea to perform this. Thanks for reading and help
Posted
by
Post not yet marked as solved
0 Replies
774 Views
I have yet to see iOS call my background task. I can get it to call it with the debug support (_simulateLaunchForTaskWithIdentifier), but not on its own. Does being foreground suppress the task call? Does being connected to the debugger (but in the background) suppress the call? Does an Xcode-installed app get its background task called? What is the Xcode scheme Run Info option “Launch due to a background fetch event"? Xcode 15b1 and iOS 17b1.
Posted
by