iOS Swift Sync data when app in background

Hi there,

I developed an iOS app in Swift and I’m trying to sync data periodically after the app enter in background mode (user leaves the app but didn’t killed it).

I implemented a BGAppRefreshTaskRequest as follow:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: AppDelegate.CREATE_EVENT_BACKGROUND_TASK_IDENTIFIER, using: nil) { task in
            self.handleAppBackgroundRefresh(task: task as! BGAppRefreshTask)
        }
}
func handleAppBackgroundRefresh(task: BGAppRefreshTask) {
        let _ = Task {
            await self.checkIfNeededToCreateEvent(task: task)
            self.scheduleCreateEventBackgroundTask()
        }
}
func scheduleCreateEventBackgroundTask() {
        let request = BGAppRefreshTaskRequest(identifier: AppDelegate.CREATE_EVENT_BACKGROUND_TASK_IDENTIFIER)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60) // Fetch no earlier than 1 minute from now

        do {
            try BGTaskScheduler.shared.submit(request)
            print("----> BG")
        } catch {
            print("[AppDelegate - scheduleCreateEventBackgroundTask] Error: Could not schedule app refresh: \(error)")
        }
 }
@MainActor
private func checkIfNeededToCreateEvent(task: BGTask) async{
        let config = realmApp.currentUser!.configuration(partitionValue: *myPartition*)
        
        print("----> A")
        let realm = try! await Realm(configuration: config, downloadBeforeOpen: .always)
        print("----> B")
        
        let customers = realm.objects(Customers.self)
        print("----> count = \(customers.count)")
}

When I simulate the background task, I have the following logs:

----> BG
2023-06-13 10:26:00.906375+0200 eDeal[10020:2160597] Starting simulated task: <decode: missing data>
----> A
2023-06-13 10:26:01.000077+0200 eDeal[10020:2160607] Sync: Connection[2]: Session[2]: client_reset_config = false, Realm exists = true, client reset = false

When I try without downloadBeforeOpen: .always, I can open my realm but, of course, I don’t have the last updates.
Can you please help me find why it is not working?


Notes:

  • I have enabled Background fetch and Background processing in the Capabilities.
  • The const AppDelegate.CREATE_EVENT_BACKGROUND_TASK_IDENTIFIER is registered in my Info.plist under Permitted background task scheduler identifiers.

Thanks for your help!

1 Like