BGProcessingTask scheduled but never executed

22 Views Asked by At

I have this swift file :

//  backgroundTask.swift
import ...

class BackgroundTask {
    static let shared = BackgroundTask()
    
    private init() {}
    
    func registerBackgroundTask() {
        let identifier = "com.noatte.mon-tempo.backgroundTask"
        let request = BGAppRefreshTaskRequest(identifier: identifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
        
        BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { task in
            self.handleBackgroundTask(task: task as! BGAppRefreshTask)
        }
           do {
              try BGTaskScheduler.shared.submit(request)
               print(request)
               print("request scheduled successfully")
           } catch {
              print("Could not schedule app refresh: \(error)")
           }
    }

    func handleBackgroundTask(task: BGAppRefreshTask) {
        print("Background task initiated")
        LocalNotificationManager.shared.scheduleNotification(title: "Titre", body: "Test 1", triggerAfterSeconds: 5)
        task.expirationHandler = {
            // This block is executed if the background task is terminated prematurely
            // Check if this block is being triggered in the console logs
            print("Background task terminated prematurely")
        }
        
        // Mark the task as completed
        task.setTaskCompleted(success: true)
        
        // Reschedule the task for the next minute
        //registerBackgroundTask()
    }   
}

My problem is that the task (handleBackgroundTask(task: BGAppRefreshTask))is never executed, even if the print Background task initiated is logged. Also I tried forcing the execution following the code in Apple documentation, and the notification was correctly sent on the device, also I tried adding a print inside the BGTaskScheduler.shared.register but it was never logged.

If someone has a solution I'd be grateful, thank you

0

There are 0 best solutions below