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

Testing/Debugging Background Session Code
I’m trying to debug background session workflows. I read the excellent article Quinn wrote here: https://developer.apple.com/forums/thread/14855 I’m not seeing the call to exit(0) work for relaunching an app when a background URL Session completes. I’m also not getting the UIApplication.willTerminateNotification in that case. I am testing on an actual device and not hooked up to the debugger. Has anything changed since that article was published? Are there new tips for debugging background URLSession relaunch workflows?
2
0
639
Aug ’23
AppIntent timing out after around 25s. Are there solutions or alternatives?
I am launching an app intent from a widget button tap, which, in turn, executes a task in the background that can take up to 40 seconds. This task fails to execute completely most times, as the time out period is around 25 to 30 seconds. Is there any way to work around the app intent time limit? User feedback is not important, as this interacts with an external physical device, so the user knows the state from looking at said device. I was considering other alternatives for when the task fails to execute completely, like prompting the user to continue the task, but this doesn't seem like a valid solution, as there is no way to do this foreground interfacing from a widget. I am completely stumped with this. This was a problem with the old Intents, and it seems like it's still a problem with the new App Intents. I wish Apple would allow developers to control how much the intent would take to timeout.
0
1
482
Aug ’23
Silent FCM Notification blocked by system
Hi! I've been working on app with Silent Background notifications using FCM and I'm facing some issue where system decides to block the receiving notification. In Console logs I get: com.apple.pushLaunch.<bundleId>:[{name: ApplicationPolicy, policyWeight: 50.000, response: {Decision: Absolutely Must Not Proceed, Score: 0.00, Rationale: [{[pushDisallowed]: Required:0.00, Observed:1.00},]}} ], FinalDecision: Absolutely Must Not Proceed}] It never proceeds in case of app being killed and another app in use. Is there a way to tell the system to proceed or to fix this somehow so we get the notification in such case and make didReceiveRemoteNotification to be called? Thanks!
1
0
460
Aug ’23
Got a Crash on: com.apple.BGTaskScheduler
whenever the background task stat running one of the UI got triggered i.e published the UI rendering part, so the crash occurred on that publisher subscribed and change the UI, so i don't think the ui doesn't load on the background task runs, so i don't use main thread operation for that UI change, this may be the reason for crash, i dont know, could you please help
1
0
370
Aug ’23
Background mode for BLE app
Hi. I have medical app that communicates with bluetooth device all the time monitoring heart rate and oxygen. I set it as background: External accessory communication, Uses BLE, Background fetch, Remote notifications, Background processing. Unfortunately after about an hour max 2 hours it stops communicating with bluetooth device and stops sending data to the server. I know in Android for example if device in similar to iOS background mode but phone plugged into power then app will never be suspended. Is there some way for the app to be always running? We can tell users to keep it powered or always in foreground. Please help.
2
0
716
Aug ’23
Is it safe to call `beginBackgroundTaskWithExpirationHandler` in `applicationWillEnterForeground`?
I wanted to understand if it is safe to call beginBackgroundTaskWithExpirationHandler in applicationWillEnterForeground or if it should only be called when the app is going to enter the background? My requirement is that I have a thread running which sends data to the server, and I want to ensure that when the app enters the background, it sends some extra information (like the app has been backgrounded and some other events that occurred while the app was in the foreground). This may take some time to complete. So, I'm trying to understand the best practice for calling beginBackgroundTaskWithExpirationHandler.
1
0
429
Aug ’23
Background API call in iOS
Hello, I am building an enterprise application, where I will be syncing user location to the backend server every 5 min for a period of 12 hr every day. I have enabled location updates and background processing for the app in Xcode, and also will be getting location permission as always from user. We are able to get the location update from the user for the whole time, but the part where we make the service call to sync with backend is delayed. It works fine for the first couple of minutes, but later we see the delay. I have also used NWConnection to directly make the service call without using URLSession, this approach is slight better comparatively, but not perfect. I have made sure "Low power mode" and "Low data mode" is disabled, also "Background App Refresh" is enabled for the application. I believe it should be possible since may app eg. WhatsApp, Telegram have a feature of sharing live location for up to 8 hrs. Is there any way where we can achieve this without delay? Thanks in advance.
1
0
695
Aug ’23
How to start a hands-free Nearby Interaction (UWB) session using Bluetooth?
Hello, Our team is working on a mobile app that uses Nearby Interaction framework (UWB technology) to get real-time high-accuracy ranging information with our third-party UWB-enabled device. So far everything works fine, background sessions included as explained in wwdc2022/10008 video. We are using Bluetooth LE to exchange the UWB parameters as recommended by Apple. Our next goal is to go for a full hands-free configuration of the UWB session. Let's think of an access control use case where UWB is used to measure the distance between the user and the door (credentials exchanged via Bluetooth). What we want to achieve is to start the UWB session without requiring the user to take the phone out of his wallet and open the access control app. What it works for us today is if the user starts the app, then switches off the screen and puts the phone into his pocket. The app is still running in background, so the Bluetooth Scan keeps working, the Bluetooth session starts, the UWB parameters exchanged and the UWB session started in the background, all good. But what if the user killed the app or never started it after reboot? How can we force the app to start from killed state when the BLE / UWB third-party accessory comes into proximity? iBeacon seems like a promising approach, but according to the forums, in iOS 16 the app will not be restarted from killed state. Is this correct? Any idea / suggestion about how to let the OS start our app when the user approaches the BLE / UWB accessory and the app is in killed state? Thanks in advance for your time. Regards.
2
0
968
Mar ’24
Making API calls after receiving a notification
Hello, I have a tasks to make an app such that once receive FCM notification, get current SSID and current location, then send it to our server, even if this app is in background (not active) or being killed from app switcher(not sure if it's the correct name, user swipe up to remove apps). Now it works for a couple of hours after putting the app to background, but with a time limit I don't know it stops working. I personally think it cannot be done, but could somebody please confirm it?
1
0
494
Jul ’23
SwiftData in background task
I wrote this simple app to try to fetch and add data to my airport Database in the background. I'm trying to add some data to the airport table in the background using swift-data, I create a loop that should add and save 100 test airports in a table but when I run the code I only get add 1 airport at the time and the number get add is random, any idea why? How to use swiftData in the background? So far not so many examples. actor JsonImporter: ModelActor { let executor: any ModelExecutor let context: ModelContext init(modelContainer: ModelContainer) { context = ModelContext(modelContainer) executor = DefaultModelExecutor(context: context) } func parseJsonDBAirport() async { for i in 1...100{ print("loop \(i)") let airport = Airport(lastPicked: Date(), icao: "test \(i)") context.insert(airport) do{ try context.save() }catch { print("Error") } } } } Using on the view: struct SettingsView: View { @Environment (\.modelContext) var mc var body: some View { Button { Task(priority: .background){ let importer = JsonImporter(modelContainer: mc.container) await importer.parseJsonDBAirport() } } label: { Text("Parse Json airport") } NavigationLink { Airports(dm: dm) } label: { HStack{ Image(systemName: "person.2.badge.gearshape.fill") Text("Airports") } } } } my main actor is following: @main struct Pilot_VisionApp: App { var dm = DataManager.shared var body: some Scene { WindowGroup { SettingsView(dm: dm) } .modelContainer(for: [UserModel.self, Flight.self, Aircraft.self, CrewModel.self, Airport.self]) } } and the airport list as following: import SwiftUI import SwiftData struct Airports: View { let dm: DataManager @Query(filter: nil, sort: [SortDescriptor(\Airport.lastPicked)], animation: .default) var airports: [Airport] var body: some View { List{ Text("Airport Contains : \(airports.count)") ForEach(airports) { apt in Text("icao: \(apt.icao ?? "")") } } } } not sure why when I press the button the loop runs correctly I get the printout 100 times but when I open the list of my airport I only see 1 airport saved, every time I press the button one more airport is added to the table but should be 100 airports every time I press the button. How shuld be use swiftdata in background? thanks
0
0
971
Jul ’23
How to refresh my iOS-App regularly?
Hi, I tried to figure out how I can get my iOS-App to refresh regularly if it is in the background. I thought about WhatsApp. Even if it is closed it updates itself in the background and checks for new messages. But how does it do this? I would like to observe the battery charging level. But my app should also observe it when I switched the screen off (locked my iPhone). I don't know how to do this. A Timer will not work, it is not available if the app is in the background. To clarify: I know how to read the battery level but I don't know how to observing the battery level when the app is in the background. I tried to learn something about the Background App Refresh function but I had no success.
1
0
390
Jul ’23
How to make my bundle run when an agent system tries screen sharing or remote management, so that I can provide second step verification by using my custom bundle?
I'm a beginner in swift. Ways I tried: Tried adding a command line tool DNC observer to call a function when any screen sharing notification triggers, but later came to know that screen sharing doesn’t give any notifications. import OSLog import Foundation os_log("TecMFA:: Starting screen sharing finder.") let dnc = DistributedNotificationCenter.default() dnc.addObserver( forName: .init("com.apple.screensharing.server"), // tried many notification names like com.apple.screensharing.curtain etc. object: nil, queue: .main ) { notification in os_log("TecMFA:: Started screen sharing deamon.") } dispatchMain() Created a server using vapor as following //configure.swift import Vapor func routes(_ app: Application) throws { // Define a route to handle POST requests to "/login" app.post("login") { req -> HTTPStatus in // Read the username and password from the request body guard let loginData = try? req.content.decode(LoginData.self) else { // Failed to parse request body or invalid data return .badRequest } let username = loginData.username let password = loginData.password print(username) print(password) // Do something with the username and password print("Received login request with username: \(username) and password: \(password)") // Return a success response return .ok } } // Define a struct to represent the request body data struct LoginData: Content { let username: String let password: String } // routes.swift import Vapor import Foundation func getLocalIPAddress() -> String? { let task = Process() task.launchPath = "/usr/sbin/ipconfig" task.arguments = ["getifaddr", "en0"] // Use "en0" for Wi-Fi, "en1" for Ethernet let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) return output } // Called before your application initializes. public func configure(_ app: Application) throws { // Register routes try routes(app) // Get the local IP address guard let localIPAddress = getLocalIPAddress() else { fatalError("Unable to get the local IP address.") } // Update the server configuration to bind to the local IP address and desired port app.http.server.configuration.hostname = localIPAddress app.http.server.configuration.port = 8080 } It didn't work when same port numbers. I tried using different port numbers but the request comes through port 5900, so 8080 cannot access it, so it didn't work either. Any corrections and suggestions are welcome.
3
1
449
Jul ’23
Background task with MFi External Accesory device
We are developing an app that is going to be used with hardware that is connected through bluethooth to the iOS device, where we use a device with an MFI external accessory, and we are using the external accessory framework, and this will require some background tasks, we understand that there is a limitation on the use on background capabilities, but we were wondering what is the best approach to gather information from the hardware while the app is running on the background? think of the Oura ring, the app is gathering some information while you are sleeping, not processing, not fully running, only gathering information. Should we doit with the BGProcesingTask? or there is an additional background strategy to this kind of use case? Thanks.
0
0
453
Jul ’23
Why must I wrap a call to call to an async/await method in a Task?
Trying to to convert my old URL functionality to SwiftUI with async/await. While the skeleton below works, am puzzled as to why I must place my call to the method within a Task? When I don't use Task I get the error: Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type From the examples I've seen, this wasn't necessary. So I either I've misunderstood something, or I am doing this incorrectly, and am looking for little but of guidance. Thank you Within my SwiftUI view: Button { Task { let request = xFile.makePostRequest(xUser: xUser, script: "requestTicket.pl") var result = await myNewURL.asyncCall(request: request) print("\(result)") } } From a separate class: class MyNewURL: NSObject, ObservableObject { func asyncCall(request: URLRequest) async -> Int { do { let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { print("error") return -1 } if httpResponse.statusCode == 200 { ... } } catch { return -2 } return 0 } }
1
0
1.9k
Jul ’23
I want to close my app after a while in background mode
I am sorry for my poor English. I know that a callback of timer is not called in background mode. I know that I should add capabilities, permissions and keys into the Info file for doing something in background mode. But I do not need any complicated task in background mode, just need to terminate my app automatically after 30 minutes in background mode. Is there a simple way for that purpose?
4
0
1.2k
Jul ’23
Dismiss Live Activities on App Termination
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?
3
2
2.2k
Jul ’23