Since some time I have tried to use background tasks in Swift: https://developer.apple.com/documentation/backgroundtasks
But for some reason I cannot get it working. I do not use simulator but build directly to my device. Iam using SwiftUI but to get it working I have enabled AppDelegate to handle the background tasks like visible below.
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
let taskId = "co.echonova.LemonAppIos.fetchGps"
// Handler for the task. My assumption is that it will print "Task did run". Also debugger does not enter this method.
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskId, using: .main) { task in
print("Task did run")
task.setTaskCompleted(success: true)
}
// Check if there are pending tasks.
BGTaskScheduler.shared.getPendingTaskRequests { request in
print("\(request.count) BGTasks pending..")
}
// Schedule the task
do {
let newTask = BGAppRefreshTaskRequest(identifier: taskId)
newTask.earliestBeginDate = Date().addingTimeInterval(10)
try BGTaskScheduler.shared.submit(newTask)
print("scheduled")
} catch {
print("failed to schedule")
}
return true
}
}
But for some reason the task never get executed. The terminal shows:
1 BGTasks pending..
scheduled
My expectation is that the terminal should print after ten seconds
1 BGTasks pending..
scheduled
Task did run
Any idea why this does not happen? I have tried a lot already but did not get it working.
earliestBeginDateis only for “don’t run sooner than specified date”, not “run it at the specified date”. That’s why we have thatlldbcommand, when you want to explicitly fire at a precise moment in time. See Starting and Terminating Tasks During Development.