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

123 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
441
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
428
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
369
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
925
Jul ’23
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
469
Jul ’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
921
Mar ’24
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
680
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
414
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
690
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
361
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
439
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
469
Aug ’23
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
617
Aug ’23
NIErrorCodeInvalidConfiguration error code using the function NINearbyAccessoryConfiguration(Accessory:BluetoothPeerIdentifier)
Ranging is working great when I'm removing the BluetoothPeerIdentifier parameter but if I want to do some background ranging, I need to be able to use the removed parameter. Somehow when I'm both AccessoryData and BluetoothPeerIdentifier parameters, I got the NIErrorCodeInvalidConfiguration error code and i can't range anymore. Do you guys have a fix for that? The parameter BluetoothPeerIdentifier is not NULL so it should work properly... Thank you, Marc
0
0
605
Aug ’23
How to use SMAppService to launch a launchAgent
I am currently making an XCode project where I plan to use SMAppService to register a launch agent so that the app can change the desktop wallpaper on a monthly basis. However, I am an amateur and have had difficulties getting the SMAppService to work. So far I have roughly followed the instructions listed in the answer here: https://developer.apple.com/forums/thread/721737 However, I still cannot get the launchd agent to run (although it does get added to the launchctl list) as I'm not fully sure how to follow those instructions. Therefore I am asking if anyone has some resources to help point me in the right direction to using the SMAppService to launch a launchAgent. Thanks,
1
1
716
Sep ’23
How to record audio in background
How can i record an audio when the app is in background? I tried on android and its working but on IOS its only recording on the foreground Its an Expo app and am using Expo Av library I have already allowed the permissions and set the UIBackgroundModes with audio "infoPlist": { ... "UIBackgroundModes": [ "audio" ] } And in the code also await Audio.setAudioModeAsync({ allowsRecordingIOS: true, playsInSilentModeIOS: true, staysActiveInBackground:true }); but once the app is in background mode it is failing to start recording. Can anyone help me how I can fix this ?
0
1
585
Sep ’23
Using Core Location in App Intent
I would like to retrieve the user's current location when they are logging some information with my App Intent. When the app has been just run, this works just fine, but if it has been force quit or not run recently, the Core Location lookup times out. I have tried logging the information and using the Core Location background mode, and I can verify that the background mode is triggering because there is an indicator on the status bar, but the background mode does not seem to fire the delegate. Is there a good way to debug this? When I run the app, everything works just fine, but I can't confirm that delegate calls are going through because I can't debug from an App Intent launch. Here is the perform method from my App Intent func perform() async throws -> some ProvidesDialog { switch PersistenceController.shared.addItem(name: name, inBackground: true) { case .success(_): return .result(dialog: "Created new pin called \(name)") case .failure(let error): return .result(dialog: "There was a problem: \(error.localizedDescription)") } } addItem calls LocationManager.shared.getCurrentCoordinates: func getCurrentCoordinates(inBackground: Bool = false, callback: @escaping (CLLocation?) -> Void) { if lastSeenLocation != nil { callback(lastSeenLocation) return } if inBackground { locationManager.allowsBackgroundLocationUpdates = true locationManager.showsBackgroundLocationIndicator = false } let status = CLLocationManager.authorizationStatus() guard status == .authorizedAlways || status == .authorizedWhenInUse else { DispatchQueue.main.async { [weak self] in self?.callback?(nil) self?.locationManager.allowsBackgroundLocationUpdates = false } return } self.callback = callback locationManager.startUpdatingLocation() } The CLLocationManager delegate didUpdateLocations then calls the callback with the location and sets allowsBackgroundLocationUpdates to false. And the callback saves the location data to Core Data. What is the best practice for using Core Location in an App Intent?
0
0
427
Sep ’23