Zorgan
Zorgan

Reputation: 9123

How to change an @ObservedObject variable in SceneDelegate?

I have a model here:

class Instance: ObservableObject {
    @Published var status: Status = .offline

which updates the following view when it changes...

struct HomeView: View {
    @ObservedObject var instance = Instance()
    var body: some View {
        Text(self.instance.status.text)
    }
}

I want to change the value of status when my app opens. E.g, in SceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Change Instance variable status to .online
    }

How can I achieve this?

Edit:

struct ContentView: View {
    @ObservedObject var auth = UserAuth()
    var body: some View {
        Group {
            if auth.uid != nil { HomeView(auth: auth) } else { LoginView(auth: auth) }
        }
    }
}

Upvotes: 1

Views: 380

Answers (2)

Asperi
Asperi

Reputation: 257493

If I correctly understood your code, in such case it is most appropriate would be to keep auth instance in SceneDelegate

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?
    let auth = UserAuth()    

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Change Instance variable status to .online
       auth.status = .online
    }

and use it it everywhere as @EnvironmentObject by inject in ContentView().environmentObject(auth)

Upvotes: 2

KevinP
KevinP

Reputation: 2738

You can simply move your Instance into your SceneDelegate and pass a reference to your HomeView. You can pass it down directly or put your Instance into the Environment, depending on your needs. Heres an example of a direct Reference:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    var instance = Instance()
    ...

    let contentView = HomeView(instance: self.instance)

    ...
    func sceneWillEnterForeground(_ scene: UIScene) {
        instance.status = ...
    }
    ...

Change your View so it isn't initializing Instance by itself:

struct HomeView: View {
    @ObservedObject var instance: Instance
    var body: some View {
        Text(self.instance.status.text)
    }
}

Upvotes: 2

Related Questions