Home > OS >  How to have a shared state across swiftUI app?
How to have a shared state across swiftUI app?

Time:08-03

I'm trying to sign in with Gmail on my swift UI MacOS app. I have the state object here

    @State var sharedUser = User.shared
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onOpenURL { url in
                  GIDSignIn.sharedInstance.handle(url)
                }
                .onAppear {
                          GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
                              if error != nil { return }
                              
                              sharedUser.signIn(user: user)
                           }
                }
        }
    }

I see that it restores the previous sign in and I make the shared User the user it returns

Over here in the content view I have a check to see if the user is logged in

    @State var user = User.shared
    var body: some View {
        VStack {
            if user.user != nil {
                Button(action: {
                    logout()
                }) {
                    Text("Sign Out")
                }
            } else {
                GoogleSignInButton(action: handleSignInButton)
            }

However user always returns nil, and I'm wondering how I can share the object value from the App Struct to the View

CodePudding user response:

  1. Make your User type conform to ObservableObject (which means it has to be class).
  2. Add @Published in front of all the properties (in User) that you want SwiftUI to detect changes.
  3. Instead of @State, use @ObservedObject.
  • Related