SwiftUI .onAppear, in esecuzione solo una volta

Aug 15 2020

In SwiftUIun'app ho un codice come questo:

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

Il mio problema è che vorrei eseguire del codice all'interno del blocco .onAppear , in modo che venga eseguito quando l'app viene visualizzata sullo schermo, dopo l'avvio o dopo essere rimasti in background per un po '. Ma sembra che questo codice venga eseguito solo una volta all'avvio dell'app e mai dopo. Mi sto perdendo qualcosa? O dovrei usare una strategia diversa per ottenere il risultato che voglio?

Risposte

5 Frankenstein Aug 15 2020 at 15:46

Dovresti osservare l'evento quando l'app sta entrando in primo piano e pubblicarlo utilizzando @Publishedil file ContentView. Ecco come:

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()
    }
}