Hi, I'm trying to schedule a background task to fetch a system parameter value at regular intervals. I've created a dummy iOS app using Xcode for the same and am making use of the new Background tasks framework to accomplish this.
I've selected the 'Background fetch' and 'Background processing' checkboxes at the Capabilities sections, and defined two new tasks in the 'Permitted background task scheduler identifiers' entry in the Info.plist file. I've added the following code into AppDelegate class to schedule the background tasks and get it triggered when my app is in the background:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
BGTaskScheduler.shared.register(
forTaskWithIdentifier: "com.mokhosla.fetchBrightness", using: nil) { task in
self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
}
return true
}
func handleAppRefreshTask(task: BGAppRefreshTask) {
scheduleBackgroundBrightnessFetch()
let brightnessOperation = BrightnessOperation(brightness: UIScreen.main.brightness.description)
task.expirationHandler = {
brightnessOperation.cancel()
}
brightnessOperation.completionBlock = {
task.setTaskCompleted(success: !brightnessOperation.isCancelled)
}
let operationQueue = OperationQueue()
operationQueue.addOperation(brightnessOperation)
}
func scheduleBackgroundBrightnessFetch() {
let taskRequest = BGAppRefreshTaskRequest(identifier: "com.mokhosla.fetchBrightness")
taskRequest.earliestBeginDate = Date(timeIntervalSinceNow: 10)
do {
try BGTaskScheduler.shared.submit(taskRequest)
} catch {
print("error: \(error.localizedDescription)")
}
}
Upon building the app and then moving it in the background, I find that the OS never trigggers the background task. I've gone through a few other threads on this forum and find other developers facing the same issue. Is there something wrong I'm doing there? Is this not the expected way to use BGTasksScheduler? Kindly help me understand what I'm doing wrong here. Thanks in advance!