0

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.

3
  • Shouldn't UIApplication.shared.backgroundRefreshStatus tell you fi the setting is on/off? But indeed, it could throw the error due to the refreshStatus Commented Jan 8 at 9:09
  • This is really a question that only Apple can answer, but given that the user can turn background app refresh on or off at any time (and it is also off when low power mode is activated) I don't think it makes sense for the schedule call to throw an error. The task was scheduled successfully. Your app never really knows if or when a task is going to execute. Just because background refresh is off when you submit the task, it doesn't mean that it will still be off when it comes time to execute (the device could have left low power mode, for example) Commented Jan 8 at 21:10
  • As Larme suggested, you can use the backgroundRefreshStatus to provide feedback to the user as to whether background refresh will occur (or to log for your purposes). Commented Jan 8 at 21:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.