SwiftUI 技巧大全之如何在 SwiftUI 中执行后台任务?

实战问题

我的目标是在 SwiftUI 中执行后台任务。

我尝试过的:

使用后台任务,但任务没有得到执行。
我的期望:任务得到执行。

我的实际结果:任务没有执行。

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

猜你喜欢

转载自blog.csdn.net/iCloudEnd/article/details/131748820