swiftui

Get the currently signed-in user Firebase in swiftUI


I want to switch to a new view when the login is successful And it will save the login state, when I close the App and open it again, no need to login again. I use combine . library .Hope you can help me. Thanks

Here is my full code. Hope you will help me


Solution

  • Firebase will tell you... you just need to ask. This is how you ask.

        let user = Auth.auth().currentUser
        if let user = user {
            // User is logged in
        }
    

    These are the FirebaseAuth iOS docs (for further information)

    Your should probably call this in the init of your LoginViewModel

        init() {
            let user = Auth.auth().currentUser
             if let user = user {
                // User is logged in
                session = User(uid: user.uid,
                               email: user.email)
            } else {
                session = nil
            }
         }
    

    Make the LoginViewModel variable session @Published like this

        class LoginViewModel: ObservableObject {
            ...
            @Published var session: User?
            ...
        }
    

    read about the Published type here

    Update

    You should add this block to your signIn() func in the LoginView in the else instead of session.isLoggedIn.toggle().

    I also recommended removing the isLoggedin var you should look at the user object in session to check if it is nil or not.

        func signIn () {
            loading = true
            error = false
            session.signIn(email: email, password: password) { (result, error) in
                self.loading = false
                if error != nil {
                    self.error = true
                    self.loading = false
                } else {
                    guard let uid = result?.user.uid,
                          let email = result?.user.email else {
                        return
                    }
                    session.session = User(uid: uid, email: email)
                }
            }
        }
    

    This is the signUp() I added. Although I recommend making it on a separate page.

        func signUp (email: String,
                     password: String,
                     handler: @escaping AuthDataResultCallback) {
                Auth.auth().createUser(withEmail: email, password: password, completion: handler)
        }
    

    Finally I would recommend to move all the login logic to the viewModel instead of the view... that's why viewModels exist.