BGTaskScheduler.shared.register() is called but the completion handler never fires

222 Views Asked by At

In a purely SwiftUI project I am trying to use the BackGround Modes in my iOS project and have enabled Background fetch in the Signing & Capabilities section of my target. I also made the entry for Permitted background task scheduler identifiers adding "com.mycompanyname.fetch" in the project info.

In the App file I added an init() function and in it have:

    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.mycompanyname.fetch", using: nil) { (task) in
        UserDefaults.standard.set("It made it", forKey: "registered")
        BackgroundTaskUtility.handleAppRefreshTask(task: task as! BGAppRefreshTask)
    }

This gets called, but the completion handler never fires, so the user defaults entry and the handleAppRefresh call are not made. I have no idea why it doesn't fire.

I am running this on an actual phone not in the simulator, and if I put the app in the background and then foreground it, and then pause it and run e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.mycompanyname.fetch"] as provided by Apple, it of course works.

Interestingly when I call let request = BGAppRefreshTaskRequest(identifier: "com.mycompanyname.fetch") followed by try BGTaskScheduler.shared.submit(request) it works (as indicated by not ending up in the catch block).

If I comment out the the call to BGTaskScheduler.shared.register(), calling try BGTaskScheduler.shared.submit(request) will then throw an exception indicating that the register call actually worked despite not calling the completion handler. So confusing.

In the end the background event never fires.

1

There are 1 best solutions below

0
On

From the description it sounds like you are registering your completion handler, but never submitting a task to the background task scheduling system.

It is expected that you need to call: try BGTaskScheduler.shared.submit(request)

https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/using_background_tasks_to_update_your_app