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

129 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

background excution lifecycle
background push or background refresh can wake app in the background. according douctument About the background execution sequence, if app is not runing, system launch app an move it directy to background. however if user tap app icon when system launch app and calling didFinishLaunchingWithOptions method, then what is execution order of app lifecycle
2
0
424
Oct ’23
How to Implement Lots of Tiny Uploads in the Background?
I am aiming to create a feature within an iOS application to backup all photos and videos from the device to a server, similar to Dropbox’s camera upload feature. Upon initiating the upload, I want to ensure the process continues even when the app moves to the background. Would utilizing Background Task Completion be the appropriate approach to maintain the upload process in the background? Furthermore, in scenarios where the background process gets interrupted and the app transitions back to the foreground, I want to resume the upload. What would be the suitable implementation to ensure the upload resumes seamlessly? Moreover, I have observed that an app named TeraBox continues its background processes for over 10 minutes after transitioning to the background. How might this prolonged background process be achieved?
1
0
384
Oct ’23
Background Task Only Executes Once or Twice, Not at Regular Intervals.
My background task, implemented as per Apple's documentation, runs only once or twice instead of running continuously one after another. Seeking assistance to resolve this problem. What I want to achieve I want to hit the jsonbin API continuously in regular intervals is there anything wrong in code? AppDelegate import UIKit import BackgroundTasks @main class AppDelegate: UIResponder, UIApplicationDelegate { let apiKey = "xxxxxxx" // jsonbin x-master-key let timestampUserDefaultsKey = "Timestamps" static let backgroundAppRefreshTaskSchedulerIdentifier = "com.process" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Register a background task if #available(iOS 13.0, *) { let status = BGTaskScheduler.shared.register( forTaskWithIdentifier: AppDelegate.backgroundAppRefreshTaskSchedulerIdentifier, using: .global()) { task in self.handleBackgroundTask(task: task as! BGProcessingTask) } print(status) } return true } func handleBackgroundTask(task: BGProcessingTask) { self.scheduleAppRefresh() task.expirationHandler = { task.setTaskCompleted(success: false) self.scheduleAppRefresh() } let backgroundQueue = DispatchQueue.global(qos: .background) backgroundQueue.async { self.postToJsonBin(prefix:"P-Background") { result in switch result { case .success(let responseJSON): // Handle the success and responseJSON print("Response JSON: \(responseJSON)") task.setTaskCompleted(success: true) case .failure(let error): task.setTaskCompleted(success: false) // Handle the error print("Error: \(error.localizedDescription)") } } } } func scheduleAppRefresh() { if #available(iOS 13.0, *) { let request = BGProcessingTaskRequest(identifier: AppDelegate.backgroundAppRefreshTaskSchedulerIdentifier) // Fetch no earlier than 15 seconds from now. request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 5) // 60 seconds // request.requiresNetworkConnectivity = true do { try BGTaskScheduler.shared.submit(request) print("bg App Refresh requested") } catch { print("Could not schedule app refresh: \(error)") } } } func postToJsonBin(prefix:String, completion: @escaping (Result<Any, Error>) -> Void) { // Define the URL for jsonbin.io with the collection ID let apiUrl = URL(string: "https://api.jsonbin.io/v3/b")! // Define your JSON data including the timestamp parameter let jsonData: [String: Any] = ["timestamp": Date().currentTimestampInIST(), "prefix":prefix] do { // Serialize the JSON data let requestData = try JSONSerialization.data(withJSONObject: jsonData) // Create the URLRequest var request = URLRequest(url: apiUrl) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(apiKey, forHTTPHeaderField: "X-Master-Key") // Replace with your API key request.setValue(prefix, forHTTPHeaderField: "X-Bin-Name") // Set the HTTP body with the serialized JSON data request.httpBody = requestData // Create a URLSession task let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { completion(.failure(error)) return } if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { if let responseData = data { do { // Parse the response data and call the completion handler let responseJSON = try JSONSerialization.jsonObject(with: responseData, options: []) completion(.success(responseJSON)) } catch { completion(.failure(error)) } } } else { completion(.failure(NSError(domain: "JsonBinErrorDomain", code: 0, userInfo: nil))) // Replace with appropriate error handling } } // Start the URLSession task task.resume() } catch { completion(.failure(error)) } } } extension Date { func currentTimestampInIST() -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "Asia/Kolkata") // Set the time zone to IST // Define your desired date format dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Get the current date and time let currentDate = Date() // Format the date as a string in IST let istTimestamp = dateFormatter.string(from: currentDate) return istTimestamp } } SceneDelegate func sceneDidEnterBackground(_ scene: UIScene) { if #available(iOS 13.0, *) { let request = BGProcessingTaskRequest(identifier: AppDelegate.backgroundAppRefreshTaskSchedulerIdentifier) request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 5 ) do { try BGTaskScheduler.shared.submit(request) print("bg App Refresh requested") } catch { print("Could not schedule app refresh: \(error)") } } }
2
0
731
Oct ’23
BGProcessingTask starts only if connected to power even if requiresExternalPower is NO
I setup a BGProcessingTask that do some work with the db and at the end sends an email. I've notice that, even if I set requiresExternalPower to false the task runs only when the device is connected to the power cable. I've tested setting the repeating time every 10 minutes. If the power cable is disconnected the task isn't launhed anuymore. After I attach the cable, waiting some minutes it restarts.
7
0
2.1k
Oct ’23
Push Notifications in Background, How to use URLSession?
From a strategy perspective I use BGAppRefreshTask and BGProcessingTasks, successfully implementing them for events triggered within the client application. But there are certain events that are best triggered from the host, such as when we deploy a new set of vendor or price lists. We are trying to implement this background process using Push Notifications. We have successfully implemented sending APNS notifications from the host and receive this .json message in. application: didReceiveRemoteNotification: fetchCompletionHandler: using this code: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler { NSLog(@"userInfo - %@", userInfo); switch (application.applicationState) { case UIApplicationStateBackground: { //Check to see if this is a configs file update background notification NSArray *dictKeys = [userInfo allKeys]; BOOL foundConfigs = NO; for (NSString *dk in dictKeys) if ([dk isEqualToString:kCONFIGSVERSION]) foundConfigs = YES; if (foundConfigs) { id configVersion = [userInfo objectForKey:kCONFIGSVERSION]; NSLog(@"AAAppDelegate configVersion - %@", configVersion); if ([ServerUtilities deviceAssociatedWithAccount]) [self.bkSessionManager retrieveAndInstallUpdatedConfigFilesWithVersion:[configVersion integerValue]]; } NSLog(@"AAAppDelegate remote notification handler"); completionHandler(UIBackgroundFetchResultNewData); } break; case UIApplicationStateActive: NSLog(@"AAAppDelegate application is active"); completionHandler(UIBackgroundFetchResultNoData); break; case UIApplicationStateInactive: NSLog(@"AAAppDelegate application is inactive"); completionHandler(UIBackgroundFetchResultNoData); break; default: break; } In the Xcode simulator running on an iPhone XS, we place the application in background and then send the APNS message from the host, receiving this .json message in the userInfo dictionary: userInfo - { "app_version" = "0.1"; aps = { "content-available" = 1; }; "configs_version" = 1; "dev_os" = 13; "os_type" = ios; } Receipt of this notification then triggers the client to initiate URLSession and retrieve the appropriate files from the host in order to update values on the client. As we are seeing inconsistent behavior we suspect that we are not implementing the URLSession properly. When setting up the URLSession should it be configured using: NSURLSessionConfiguration defaultSessionConfiguration or NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: ? This is important to know since using backgroundSession requires us to set up the sessions as download tasks and the defaultSession as data tasks. I have tried various combinations so far without success. Any leads here will help...
1
0
480
Oct ’23
Moving to Fewer, Larger Transfers
Note Much of this content has been rolled into URL Loading System documentation, but I’m leaving this doc here for my own reference. URLSession background sessions are optimised for transferring a small number of large resources. Moreover, it’s best if the transfer is resumable. This design makes the best use of client device resources and the available network bandwidth. If your app runs a lot of tasks in a background session, you should rethink its design. Below you’ll find a number of options you might consider. Most of these options require server-side support. If your server does not have this support, and you can’t add it — perhaps you’re writing a client app for a server you don’t control — you won’t be able to implement these options directly. In that case consider creating your own server that sits between your app and the final server and implements the necessary smarts required to optimise your app’s network usage. If that’s not possible, a final option is to not use a background session but instead take advantage of the BackgroundTasks framework. See BackgroundTasks Framework, below. Basics The basic strategy here is to have the sender (the server for a download, your app for an upload) pack the data into some sort of archive, transfer that archive over the network, and then have the receiver unpack it. There are, however, a number of complications, as described in the subsequent sections. Archive Format The obvious choices for the archive format are zip and tar. macOS has lots of options for handling these formats but none of that support is present on iOS (r. 22151959). OTOH, it’s easy to find third-party libraries to fill in this gap. Incremental Transfers It’s common to have a corpus of data at one end of the connection that you need to replicate at the other. If the data is large, you don’t want to transfer the whole thing every time there’s an update. Consider using the following strategies to deal with this: Catalogue diff — In this approach the receiver first downloads a catalogue from the sender, then diffs its current state against that catalogue, then requests all the things that are missing. Alternatively, the receiver passes a catalogue of what it has to the sender, at which point the sender does the diff and returns the things that are missing. The critical part is that, once the diff has been done, all of the missing resources are transferred in a single archive. The biggest drawback here is resume. If the sender is working with lots of different receivers, each of which has their own unique needs, the sender must keep a lot of unique archives around so it can resume a failed transfer. This can be a serious headache. Versions — In this approach you manage changes to the data as separate versions. The receiver passes the version number it has to the sender, at which point the sender knows exactly what data the receiver needs. This approach requires a bit more structure but it does avoid the above-mentioned problem with resume. The sender only needs to maintain a limited number of version diffs. In fact, you can balance the number of diffs against your desire to reduce network usage: Maintaining a lot of diffs means that you only have to transfer exactly what the receiver needs, while maintaining fewer diffs makes for a simpler server at the cost of a less efficient use of the network. Download versus Upload The discussion so far has applied equally to both downloads and uploads. Historically, however, there was one key difference: URLSession did not support resumable uploads. IMPORTANT Starting with iOS 17, URLSession supports resumable uploads. See WWDC 2023 Session 10006 Build robust and resumable file transfers for the details. The rest of this section assumes that you don’t have access to that support, either because you’re working on an older system or because the server you’re uploading to doesn’t support this feature. When doing a non-resumable upload you have to balance the number of tasks you submit to the session against the negative effects of a transfer failing. For example, if you do a single large upload then it’s annoying if the transfer fails when it’s 99% complete. On the other hand, if you do lots of tiny uploads, you’re working against the URLSession background session design. It is possible to support resumable uploads with sufficient server-side support. For example, you could implement an algorithm like this: Run an initial request to allocate an upload ID. Start the upload with that upload ID. If it completes successfully, you’re done. If it fails, make a request with the upload ID to find out how much the server received. Start a new upload for the remaining data. Indeed, this is kinda how the built-in resumable upload support works. If you’re going to implement something like this, it’s best to implement that protocol. (r. 22323347) BackgroundTasks Framework If you’re unable to use an URLSession background session effectively, you do have an alternative, namely, combining a standard session with the BackgroundTasks framework, and specifically the BGProcessingTaskRequest. This allows you to request extended processing time from the system. Once you’ve been granted that time, use it to run your many small network requests in a standard session. The main drawback to this approach is latency: The system may not grant your request for many hours. Indeed, it’s common for these requests to run overnight, once the user has connected their device to a power source. Background Assets Framework If you’re using URLSession to download assets for your app or game, check out the Background Assets framework. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Revision History 2023-09-27 Added information about the new resumable upload support. Added the Background Assets Framework section. Made significant editorial changes. 2022-01-31 Fixed the formatting and tags. Added a link to the official docs. 2018-03-24 Added the BackgroundTasks Framework section. Other editorial changes. 2015-08-18 First written.
0
0
5.3k
Sep ’23
Seizure Alert App requiring continuous background execution
Hello! I am a student at a tertiary Epilepsy Center. Our team is building an open source seizure alert app for the apple watch that will undergo a clinical trial. A well conducted clinical trial is crucial for convincing insurance to pay for apple watches, which correlates with tech adoption. This imposes some restrictions on data collection. Our use case requires that the app run continuously as seizures are not predictable. The documentation on extended runtime sessions recommended the smart alarm mode which lasts for 30 minutes. Individuals would not use an alarm system that only works 30 minutes at a time. Is there any way we could deploy the alarm continuously? The requirements for the background execution are two fold: During model development phase the app would need to continuously collect data from accelerometer, gyro-meter, magnetometer, blood oxygen and EKG. I understand these are very demanding tasks so even one sensor would be good to start with. The app would then upload this to a server over the web (perhaps using CloudKit). If continuous data collection is not possible then what is the longest guaranteed latency between samples? What amount of CPU usage would be permissible and how would it impact sampling rates? During deployment the app would need to run an ML model in the background continuously. We have chosen a light-weight model[1] that has been optimized for mobile devices. It has ~ 1.3 million parameters. What would be the maximum guaranteed latency for running a ML model in the background? Please let me know if you need any more information. Thank you. Reference: Lightweight Transformers for Human Activity Recognition on Mobile Devices, Sannara EK, François Portet, Philippe Lalanda. arXiv:2209.11750
0
0
457
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
421
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
575
Sep ’23
Background fetch after app is force-quit
Hello! Can someone please confirm whether or not an app will trigger background fetch after it has been force-quit by the user? Currently my app works performs background fetches correctly when it has been backgrounded, but after force-quitting the app it stops fetching. Specifically I am referring to scheduled background fetches, not fetches initiated by notifications - although I am interested to know if that would be an alternative. I've tried searching online and there's a lot of confusing and contradictory information about this - including old Apple documentation that explicitly says it will not launch, however that documentation has since been removed. The new documentation does not explicitly mention the force-quit scenario. Can anyone please confirm? Thanks!
12
2
5.1k
Sep ’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
683
Sep ’23
Background Tasks and time running in background
Our application allows people to back up their content (Photos / Videos) into the cloud. To have our backup working more efficiently while the application is in background, we have implemented background tasks. We schedule refresh and processing task (BGProcessingTask). Processing task is used for uploading content. We are looking into improving the number of triggers for processing tasks. There are one or two triggers in 24 hours but not as frequently as we expected. We did an exercise to compare google photo v/s our application: the time google gets to execute in background is 6 times more than personal cloud. What are the possible reason for this difference.  See some sample code below. We were lucky to have an appointment for a tech talk with @George V. from Apple and he suggested to use BGProcessingTask and set a flag to defer those tasks to run at a time where the device was less used. We do work with BGProcessingTask and are using the flags request.requiresNetworkConnectivity and request.requiresExternalPower. Where it's not clear for me is: would setting requiresExternalPower to true prevent our app to run in background while the device is not plugged? Any guidance would be appreciated :) Maybe @George, if you're available. Thanks import UIKit import BackgroundTasks @main class AppDelegate: UIResponder, UIApplicationDelegate {     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {         registerBgTasks()         //registerBatteryBgTasks()         return true     }     func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {     }     func registerBgTasks() {         BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.photos-upload",                                            using: nil) { (task) in             self.handleProcessingTask(task: task as! BGProcessingTask)         }     }     func registerBatteryBgTasks() {         BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.photos-upload-power",                                            using: nil) { (task) in             self.handlePowerProcessingTask(task: task as! BGProcessingTask)         }     }     func handlePowerProcessingTask(task: BGProcessingTask) {         let startTime = Date()         let taskId = task.identifier         if let url = URL(string: "https://imaging.nikon.com/lineup/dslr/df/sample.htm") {             let session = URLSession.shared             let networkTask = session.dataTask(with: url) { data, _, _ in             }             networkTask.resume()         }         task.expirationHandler = {             let endTime = Date()             let diffComponents = Calendar.current.dateComponents([.second], from: startTime, to: endTime)             let taskEntry = TaskEntry(taskId: taskId, taskLaunchedTime: DateUtility.readableDate(date: startTime),                                       taskExpirationTime: DateUtility.readableDate(date: endTime),                                       taskTotalTime: "\(diffComponents.second ?? 0)")             let fileName = "\(Date().timeIntervalSince1970)power.plist"             APIPreferencesLoaderPower.write(preferences: TaskArray(tasks: [taskEntry]), fileName: fileName)             task.setTaskCompleted(success: true)         }     }     func handleProcessingTask(task: BGProcessingTask) {         let startTime = Date()         let taskId = task.identifier         if let url = URL(string: "https://imaging.nikon.com/lineup/dslr/df/sample.htm") {             let session = URLSession.shared             let networkTask = session.dataTask(with: url) { data, _, _ in             }             networkTask.resume()         }         task.expirationHandler = {             let endTime = Date()             let diffComponents = Calendar.current.dateComponents([.second], from: startTime, to: endTime)             let taskEntry = TaskEntry(taskId: taskId, taskLaunchedTime: DateUtility.readableDate(date: startTime),                                       taskExpirationTime: DateUtility.readableDate(date: endTime),                                       taskTotalTime: "\(diffComponents.second ?? 0)")             let fileName = "\(Date().timeIntervalSince1970)normal.plist"             APIPreferencesLoader.write(preferences: TaskArray(tasks: [taskEntry]), fileName: fileName)             task.setTaskCompleted(success: true)         }     } } other class: func scheduleBgTask() {         let request = BGProcessingTaskRequest(identifier: "com.synchronoss.cloud.photos-upload")         request.requiresNetworkConnectivity = true         request.requiresExternalPower = false         do {             try BGTaskScheduler.shared.submit(request)         } catch {             print("error")         }     }     func schedulePowerBgTask() {         let request = BGProcessingTaskRequest(identifier: "com.synchronoss.cloud.photos-upload-power")         request.requiresNetworkConnectivity = true         request.requiresExternalPower = true         do {             try BGTaskScheduler.shared.submit(request)         } catch {             print("error")         }     }
3
0
2.3k
Sep ’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
664
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
608
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
594
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
459
Aug ’23
Check if Background URLSession with identifier exists
I have a working background URLSession. I know that upon creating an URLSession with the same session identifier I get a "background URLSession with identifier x already exists" message. I know that I can store the session and call .finishTasksAndInvalidate() on it if needed. My use case is that if the application terminates, and the user relaunches the application before the background task completes, I need to be able to check if a background URLSession with the same identifier exists, and if it does, restitute the application state with the same handlers (so that I can update a UIProgressView for example). I have two questions: How do I check that a background URLSession with a given identifier already exists? Does the AppDelegate completion handler still get called if the application was terminated and relaunched?
5
0
1.9k
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
426
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
353
Aug ’23