I'm building an app with background fetch following the instructions provided in the BGTaskScheduler documentation, but unfortunately it's not working, and I can't find a way to debug it. The problem is that the launch handler that I'm registering never gets triggered even if I try simulating a background fetch from the debug menu or creating a scheme to launch the app for background fetch. I'm sure that the request method from BGTaskScheduler is returning true because I'm calling it inside an assert and running for debugging, I have also checked whether background app refresh is disabled either for the app or the whole device and it's not. I have even created a small app to use as a minimum working example and it has the same problem so I don't know what to do next.
Here's the code from AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let taskIdentifiers = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers")! as! [String]
assert(BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifiers[0], using: nil, launchHandler: {[unowned self] in self.backgroundFetch(task: $0 as! BGAppRefreshTask)}))
scheduleBackgroundFetch(identifier: taskIdentifiers[0])
return true
}
private func backgroundFetch(task: BGAppRefreshTask) {
print(#function)
scheduleBackgroundFetch(identifier: task.identifier)
task.expirationHandler = {Client.shared.cancelRefresh()}
let operation = BackgroundFetchOperation()
operation.completionBlock = {task.setTaskCompleted(success: !operation.isCancelled)}
task.expirationHandler = {operation.cancel()}
OperationQueue.main.addOperation(operation)
}
private func scheduleBackgroundFetch(identifier: String) {
let request = BGAppRefreshTaskRequest(identifier: identifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 60.0)
try! BGTaskScheduler.shared.submit(request)
}
I'm using Xcode 11.5 on MacOS 10.15.5 and am testing on a real device with iOS 13.5.1.
Can anyone figure out what I'm doing wrong here, or perhaps suggest other things that I should look into and might not be considering?
Thanks in advance!
Selecting any option will automatically load the page