folks. In my ios app with SwiftUI, I ma trying to implement fetch data in background in order to update my app with fresh data from the Back End. In order to do it, I am trying to implement it in the Background as you do, but it doesn't work on my iPad. It works fine on debugging with e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"TASK_IDENTIFIER"]. I followed this article Background tasks in SwiftUI this one New BackgroundTask in SwiftUI and How to Test It and this WWDC22 video
Here a steps I've made to implement it.
- Added Background capability in Target -> Signin && Capabilities with "Background fetch" and "Background processing" being selected.
- Then in Info I've added "Permitted background task scheduler identifiers" where I also added my task id.
- I've created an async function where I schedule it, and I also thro notification in case there is an issue (This is only for testing..).
func sheduleBackgroundTask() async { let request = BGAppRefreshTaskRequest(identifier: "TASK_IDENTIFIER") request.earliestBeginDate = Calendar.current.date(byAdding: .second, value: 30, to: Date()) do { try BGTaskScheduler.shared.submit(request) print("DEBUG: Background Task Scheduled!") } catch(let error) { print("DEBUG: Scheduling Error \(error.localizedDescription)") let content = UNMutableNotificationContent() content.title = "Background Task Failed!!!" content.subtitle = "Message: \(error.localizedDescription)" do{ try await UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "NOTIFICATION_IDENTIFIER", content: content, trigger: UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false))) } catch{ print("DEBUG: Failed notify user \(error.localizedDescription)") } errorMessage = "Failed failed schedule background task. Message: \(error.localizedDescription)" } } Then I have created a function where I fetch data from the server and save fetched data locally using Realm.
On apper I run configuration function for notifications and schedule background task.
.onAppear{ configurePushNotification() Task{ await sheduleBackgroundTask() } } - Then I register my background task here.
.backgroundTask(.appRefresh("TASK_IDENTIFIER")) { await sheduleBackgroundTask() let _ = await refreshAppData() } I've builded and uploaded my app on my iPad, left it for weekend, but without any changes.