简体   繁体   中英

Firebase authentication in SwiftUI

i looked at solutions for firebase authentication online and on here. I haven't found a solution to implement a listener for firebase authentication.

Older solutions use the following code for a listener. i used it and gives an error.

  • cannot assign the value of type 'User.Type' to the User.

//Below is the following code i used for the listener

func listen() {
   handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
   if let user = user {
      self.session = User
   } else {
     self.session = nil
            }
        })
    }

//this is the user model below

struct User {
    var uid: String
    var email: String
}

If you'd like to use your own User model like this (as opposed to using the User object that Firebase provides), you could do this:


func listen() {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            if let user = user {
                self.session = User(uid: user.uid, email: user.email ?? "") //the ?? "" provides a default value in case the email provided by Firebase is nil
            } else {
                self.session = nil
            }
        })
}

However, it might be easier to get rid of your own User model code and just use the one that Firebase provides. So, once you've deleted your struct User { } code, you could just do this:

func listen() {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            if let user = user {
                self.session = user
            } else {
                self.session = nil
            }
        })
}

Since your app and Firebase both provide User objects, you may run into namespace collisions (where two types share the same name) unless you change the name of your User struct (or, implement the second suggestion I gave). See: Swift's standard library and name collision

You could do it like this in your ViewModel:

@Published var session = UserModel()

func listenAuth() {
    listenerAuth = Auth.auth().addStateDidChangeListener { (auth, user) in
        if let user = user {
            self.session = UserModel(uid: user.uid, email: user.email ?? "")
        } else {
          self.session = nil
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM