Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have a shared state across swiftUI app?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    @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

>Solution :

  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 @ObservableObject.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading