當應用程式進入后臺時,我想從模型檔案中做一些事情,比如停止計時器或其他事情。但是當我運行應用程式并檢查它在應用程式處于前臺scenePhase時回傳的值時。.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()
}
}
uj5u.com熱心網友回復:
仔細閱讀第一句話到最后:

更新:
你有什么建議來實作我在模型檔案中描述的邏輯?
將環境移動到視圖,它應該在哪里,并在視圖有它或檢測到它的變化時將其注入模型中,例如
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 = $0 // << update !!
}
.onAppear {
self.model.scenePhase = scenePhase // << initial !!
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483962.html
上一篇:協議中的默認初始化程式
