How to perform background tasks in SwiftUI?

combat problem

My goal is to perform background tasks in SwiftUI.

What I have tried:

A background task is used, but the task is not executed.
My expectations: Tasks are executed.

My actual result: the task is not executed.

import SwiftUI

@main
struct WeatherAppApp: App {
    @StateObject private var imageStore = ImageStore()
    
    var body: some Scene {
        WindowGroup {
            ContentView(imageStore: imageStore)
        }
        .backgroundTask(.appRefresh("randomImage")) {
            await refreshAppData()
        }
    }
    
    func refreshAppData() async {
        print("\(type(of: self)) \(#function) triggered")
        
        let content = UNMutableNotificationContent()
        content.title = "A Random Photo is awaiting for you!"
        content.subtitle = "Check it now!"
        
        if await fetchRandomImage() {
            try? await UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "test", content: conten

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/131748820