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:
- Make your
User
type conform toObservableObject
(which means it has to beclass
). - Add
@Published
in front of all the properties (inUser
) that you want SwiftUI to detect changes. - Instead of
@State
, use@ObservedObject
.