为什么 scenePhase 值是 .background 而应用程序在前台?

Why scenePhase value is .background while the app is in the foreground?

我想在应用程序进入后台时从模型文件中执行某些操作,例如停止计时器或其他操作。但是当我 运行 应用程序并检查 scenePhase 值时它 returns .background 而应用程序在前台。

import SwiftUI
import Combine

class Model {
    @Environment(\.scenePhase) var scenePhase
    var timerSubscription: AnyCancellable?
    init() {
        timerSubscription = Timer.publish(every: 1, on: .main, in: .common).autoconnect().sink { _ in
            if self.scenePhase == .background {
                // do something when the app goes to the background.
            }
            print(self.scenePhase) // print background while the app is in the foreground.
        }
    }
}

struct ContentView: View {
    var model = Model()
    var body: some View {
        Text("Hello, world!")
            .padding()
            
    }
}

仔细阅读第一句到最后:

更新:

what do you suggest to achieve the logic I described in the model file?

将环境移动到视图,它应该在的位置,并在视图拥有它或检测到它的变化时将其重新注入模型,例如

class Model {
    var scenePhase: ScenePhase?
    var timerSubscription: AnyCancellable?
    init() {
        timerSubscription = Timer.publish(every: 1, on: .main, in: .common).autoconnect().sink { _ in
            if self.scenePhase == .background {
                // do something when the app goes to the background.
            }
            print(self.scenePhase ?? .none) // print background while the app is in the foreground.
        }
    }
}

struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase  // << here !!
    var model = Model()

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onChange(of: scenePhase) {
               self.model.scenePhase = [=10=]  // << update !!
            }
            .onAppear {
               self.model.scenePhase = scenePhase  // << initial !!
            }
    }
}