We have implemented BGAppRefreshTask in our iOS Swift project. If the device's background app refresh is off, then below line of code is not throwing any error. Ideally it should throw BGTaskSchedulerErrorCodeUnavailable if background app refresh is disabled.
try BGTaskScheduler.shared.submit(request)
Sample Code:
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.bgTaskIdentifier",
using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
}
func sceneDidEnterBackground(_ scene: UIScene) {
scheduleAppRefresh()
print("Entered Background") // Prints "Entered Background"
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.example.bgTaskIdentifier")
request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
// This catch block is not executed even when background app refresh is disabled in settings.
print("Could not schedule app refresh: \(error)")
}
}
Note: If background app refresh is enabled on settings, then BGAppRefresh works fine.
I have tried physical device (iPhone 14 - iOS 18.1)
We need this error for logging purpose.
UIApplication.shared.backgroundRefreshStatustell you fi the setting is on/off? But indeed, it could throw the error due to the refreshStatusbackgroundRefreshStatusto provide feedback to the user as to whether background refresh will occur (or to log for your purposes).