12

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

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

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

4

2 回答 2

13

您必须在应用程序进入前台时观察事件并将其发布@PublishedContentView. 就是这样:

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)
    }
}
于 2020-08-15T08:46:38.723 回答
9

如果您要链接到 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")
                }
            }
    }
}
于 2021-04-14T07:16:43.017 回答