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

137 Posts
Sort by:
Post not yet marked as solved
2 Replies
905 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?) -> 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
454 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
275 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
296 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
812 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
340 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
436 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
801 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
854 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
1.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
793 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
Post not yet marked as solved
1 Replies
558 Views
I did some research and found that we can add our app by bundling a 'helper app' inside the main app's Contents/Library/LoginItems. Then in the main app (say from app delegate didlaunchwithoptions), call SMLoginItemSetEnabled and pass it the bundle identifier of the helper app and flag=true. This is way, when the main app is launched, it will configure the helper app as the 'login item', and that helper app will be launched automatically upon system login. Then in the helper app launch process, check if the 'main app' is not running, open it by using its path/url. But we also want that users are not able to quit (or force-quit) the main app (it's a security app). Or at least, if they kill the app, it should be relaunched automatically. Will just doing the above achieve all this? app should be launched upon system login app should be launched if it's killed by any way If not, what are the options?
Posted
by
Post not yet marked as solved
0 Replies
530 Views
I get that iOS decides if it will call your task, but I let my app run overnight and it never once called a task that I schedule for about 20 min in the future. If I trigger it via the debugging options here it works fine, but never has the OS called me back.
Posted
by
Post not yet marked as solved
0 Replies
512 Views
Hello, I have been working with Core Location to be able to obtain the location in real time, when the app is in the background and when it has been closed, but since the app is closed it is not possible to continue obtaining the location. These are my settings:
Posted
by
Post not yet marked as solved
1 Replies
480 Views
How do I schedule a background task in my SwiftUI-based Watch app? When I call the following method: WKApplication.shared() .scheduleBackgroundRefresh( withPreferredDate: Date.init(timeIntervalSinceNow: 15.0 * 60.0), userInfo: "MY_FIRST_UPDATE" as NSSecureCoding & NSObjectProtocol) { error in if error != nil { // Handle the scheduling error. fatalError("*** An error occurred while scheduling the background refresh task. ***") } print("*** Scheduled! ***") } the app crashes: 2023-06-21 16:04:48.730140+0900 MyWatchApp[416:109084] [default] -[WKApplication scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:]:131: Critical failure. Simulating crash: Condition failed:"NO". -[WKApplication scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:] requires that your WKApplicationDelegate (null) implement handleBackgroundTasks: My app is defined as follows: @main struct MyWatchApp: App { @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate @StateObject var viewModel = MainViewModel.shared var body: some Scene { WindowGroup { ContentView() ... // bunch of stuff here } .backgroundTask(.appRefresh) { context in // I want to perform background task here await viewModel.handleBackgroundRefresh() } } } class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { ... } func applicationDidBecomeActive() { ... } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // just in case, though this is not helping... } } I'm just following your instructions here: https://developer.apple.com/documentation/watchkit/background_execution/using_background_tasks Do I need to put some entry in my Info.plist? Or any capability I need to add? (I've added "Background Modes" with "Remote notifications" checked because I'm using CloudKit) Any help is very much appreciated!
Posted
by
Post not yet marked as solved
3 Replies
1.8k Views
I support Live Activities in my app, and am unable to dismiss Live Activities when the app gets closed from the background. Currently, I subscribe to the willTerminateNotification notification in order to perform actions when the app gets terminated. This guys triggered when the app gets terminated in the foreground. However, if it gets terminated from the background, it does not get triggered and my Live Activity stays after the app gets closed. How can I prevent this from happening?
Posted
by
Post not yet marked as solved
2 Replies
361 Views
I'm developing an app that will allow its user to launch it, put the phone in his pocket and go though his working shift. The app is designed with security at its heart, it will always track the user position, detect motionless, falls or shocks with the accelerometers, allow to program delayed alarms, etc... My problem is that after some time, iOS suspend and kill my app because the phone's holder is not moving, so there is no location update. I have looked everywhere to find that mu use case couldn't be implemented on iOS, and thus only fits Android. Is there a way to
Posted
by
Post not yet marked as solved
0 Replies
535 Views
Hi All I can run the nearby interaction even the apps is in background, while there is a distance information in the accessory side, the apps invoke delegate function "didRemove nearbyObject" with timeout periodically. is there any way to disable the timeout when it is running in background? Or anything I did wrong so that the session keep timeout while there is distance measurement in accessory side, please anyone help. Thanks in advance
Posted
by