Simulate Background Task' Not Printing to Console in Simulator using SwiftUi

129 Views Asked by At

Based on documentation from here Using background tasks to update your app

I've implemented a background task in my AppDelegate to print "Hello World - Performing background task" when app is in background. However, when I run the app in the Simulator and use the Debug menu to 'Simulate Background Fetch', nothing is printed in the console. I am using Simulator with iOS 17.0 version. What is wrong here and why I cant simulate the background task with logging something to the console?

  • "Background fetch". is checked

  • Permitted background task scheduler identifiers are set

     import UIKit
     import BackgroundTasks
     class AppDelegate: UIResponder, UIApplicationDelegate {
    
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         // Register background task
         BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.myapp.refresh", using: nil) { task in
             self.handleAppRefresh(task: task as! BGAppRefreshTask)
         }
    
    
         return true
     }
    
     func scheduleAppRefresh() {
         let request = BGAppRefreshTaskRequest(identifier: "com.example.myapp.refresh")
         request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // Fetch no earlier than 15 minutes from now
    
         do {
             try BGTaskScheduler.shared.submit(request)
         } catch {
             print("Could not schedule app refresh: \(error)")
         }
     }
    
     func handleAppRefresh(task: BGAppRefreshTask) {
         scheduleAppRefresh() // Schedule a new refresh task
    
         //background task logic here
         print("Hello World - Performing background task")
    
         task.expirationHandler = {
    
         }
    
         task.setTaskCompleted(success: true)
     }
    

    }

0

There are 0 best solutions below