将backgroundTask添加到WindowGroup会破坏AccentColor

问题描述 投票:0回答:1

我正在开发一个相当简单的 iOS 应用程序。我将资产中的 AccentColor 设置为绿色,应用程序中的每个按钮都变成绿色。当我将

.backgroundTask(.appRefresh("some identifier"))
添加到我的应用程序内的 WindowGroup 时,所有按钮突然变成蓝色。

这是代码:

import SwiftUI
import SwiftData

@main
struct MyApp: App {
    @Environment(\.scenePhase) var scenePhase
    @Environment(\.modelContext) private var modelContext
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            /* list of models */
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
        .onChange(of: scenePhase, initial: true) { newPhase, _ in
            if newPhase == .active {
                UNUserNotificationCenter.current().setBadgeCount(0)
            } else if newPhase == .background {
                scheduleAppRefresh()
            }
        }
        // Adding this .backgroundTask brakes AccentColor. Color on all buttons is blue
        // instead of AccentColor (which should be green).
        // If I remove whole .backgroundTask, AccentColor works.
        .backgroundTask(.appRefresh("com.mydomain.someapp.rescheduleNotifications")) {
            await rescheduleNotifications()
        }
    }
    func rescheduleNotifications() async {
        scheduleAppRefresh()
        NotificationManager.CreateNotifications(modelContainer: sharedModelContainer)
    }
}

这只发生在真正的 iPhone 上。它在模拟器上运行得非常好。有什么想法吗?

ios swift swiftui
1个回答
0
投票

这似乎是由

@Environment(\.scenePhase) var scenePhase
引起的 iOS 18 错误。

如果将其删除,您应该会看到您恢复了强调色。

您可以保留 .tint() 修复,或将

.onChange(of: scenePhase, initial: true)
移至
ContentView
内,但请注意,由于其工作方式,这可能会出现问题:

如果您从应用程序实例中读取阶段,您将获得反映应用程序中所有场景阶段的聚合值。如果有任何场景处于活动状态,则应用程序会报告 ScenePhase.active 值;如果没有活动场景,则应用程序会报告 ScenePhase.inactive 值。这包括从单个场景声明创建的多个场景实例;例如,来自 WindowGroup。当应用程序进入 ScenePhase.background 阶段时,预计该应用程序很快就会终止。

https://developer.apple.com/documentation/swiftui/scenephase

© www.soinside.com 2019 - 2024. All rights reserved.