Reputation:
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.
//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
}
Upvotes: 2
Views: 969
Reputation: 52337
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
Upvotes: 1
Reputation: 3396
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
}
}
}
Upvotes: 1