0

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.

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
jameri
  • 19
  • 4
  • If User is-a ObservableObject then use @StateObject instead, if not then make it such and use as stated before. – Asperi Aug 02 '22 at 11:43
  • Oh wow that worked. I had User as NSObject but I changed it to ObservalbleObject. Thanks! Wish I can checkmark a comment – jameri Aug 02 '22 at 11:56
  • Inject EnvironmentObject into the app https://stackoverflow.com/questions/68876216/how-to-declare-global-state-variables-in-swiftui – Anton Tropashko Nov 09 '22 at 13:20

1 Answers1

1
  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.
narek.sv
  • 845
  • 5
  • 22
  • You should use `StateObject` instead of `ObservableObject`. – Timmy Aug 02 '22 at 12:29
  • 1
    I would argue that. You have to use `@StateObject` if the view is the owner of that object, but since it's singleton, `@ObservedObject` will fit better. – narek.sv Aug 02 '22 at 12:43
  • Yes a singleton but the object should be called Store and have a User struct as an @Published property – malhal Aug 02 '22 at 14:57