SwiftUI Background Tasks iOS 17

I'm trying to add Background Tasks to my SwiftUI app using the modifier backgroundTask(_:action:). I've been unable to get a working example, nothing ever updates in my app in the "background".

I've added the identifier to the permitted background task scheduler identifiers , enabled the required background modes capabilities. Any help would be appreciated.

It appears that neither appRefresh nor urlSession background tasks are effective in handling the update of JSON data in my app. Also which background task would be best suited for updating json data for my app?

When debugging and launching using e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"apprefresh"] doesn't get called on a real device.

App

struct MyApp: App {
    @State private var viewModel = ViewModel()
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(viewModel)
        }
        .backgroundTask(.appRefresh("apprefresh")) {
            scheduleAppRefresh()
            await viewModel.appRefresh()
        }
        .backgroundTask(.urlSession("apprefresh")) {
            scheduleAppRefresh()
            await viewModel.urlSession()
        }
        .onChange(of: phase) {
            switch phase {
            case .background: scheduleAppRefresh()
            default: break
            }
        }
    }
    
    func scheduleAppRefresh() {
        let request = BGAppRefreshTaskRequest(identifier: "apprefresh")
        request.earliestBeginDate = .now.addingTimeInterval(15 * 60)
        try? BGTaskScheduler.shared.submit(request)
    }
}

ViewModel

@Observable
class ViewModel {
    
    func appRefresh(
    ) async {
    }
    
    func urlSession(
    ) async {
        let config = URLSessionConfiguration.background(
            withIdentifier: "apprefresh"
        )
        config.sessionSendsLaunchEvents = true
        let session = URLSession(
            configuration: config
        )
        let request = URLRequest(
            url: URL(
                string: ""
            )!
        )
        let response = await withTaskCancellationHandler {
            try? await session.data(
                for: request
            )
        } onCancel: {
            let task = session.downloadTask(
                with: request
            )
            task.resume()
        }
    }
}
SwiftUI Background Tasks iOS 17
 
 
Q