SwiftUI .onAppear,只有 运行 一次

SwiftUI .onAppear, only running once

SwiftUI 应用程序中,我有这样的代码:

var body: some View {
    VStack {
        Spacer()
        ........
    }
    .onAppear {
      .... I want to have some code here ....
      .... to run when the view appears ....
    }
}

我的问题是我想 运行 .onAppear 块中的一些代码,以便在应用程序出现时得到 运行屏幕,启动后或在后台运行一段时间后。但似乎这段代码只在应用程序启动时出现 运行 一次,之后就再也没有了。我错过了什么吗?或者我应该使用不同的策略来获得我想要的结果?

您必须在应用程序进入前台时观察事件并使用 @Published 将其发布到 ContentView。方法如下:

struct ContentView: View {

    @ObservedObject var observer = Observer()

    var body: some View {
        VStack {
            Spacer()
            //...
        }
        .onReceive(self.observer.$enteredForeground) { _ in
            print("App entered foreground!") // do stuff here
        }
    }
}

class Observer: ObservableObject {

    @Published var enteredForeground = true

    init() {
        if #available(iOS 13.0, *) {
            NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIScene.willEnterForegroundNotification, object: nil)
        } else {
            NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        }
    }

    @objc func willEnterForeground() {
        enteredForeground.toggle()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

如果您链接到 iOS14,那么您可以利用新的 scenePhase 概念:

@Environment(\.scenePhase) var scenePhase

如果注入此 属性 环境,您可以在三个条件下进行测试:

switch newPhase {
    case .inactive:
        print("inactive")
    case .active:
        print("active")
    case .background:
        print("background")
}

所以,一起:

struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase

    var body: some View {
        Text("Hello, World!")
            .onChange(of: scenePhase) { newPhase in
                switch newPhase {
                    case .inactive:
                        print("inactive")
                    case .active:
                        print("active")
                    case .background:
                        print("background")
                }
            }
    }
}