Reputation: 13
I am fairly new to coding and have started using firebase as a back end server for an application i am creating in Xcode using swift.
The app itself will have one login page but 3 separate types of users. The admin will have different permissions to the other 2 users.
The code I currently have is:
FIRAuth.auth()?.signIn(withEmail: username!, password: password!, completion: { (user, error) in
if error == nil {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "AdminVC")
self.present(vc!, animated: true, completion: nil)
}
The code is getting the email and password for the authentication page. But because of the 3 different types of users I don't want them all going to the 'AdminVC' view controller.
Is there a way of getting the 2 other users to go to their own view controllers using this authentication method?
Upvotes: 1
Views: 2383
Reputation: 3143
If you want to store a type for a user you have to use the database. Like this
When the user logs in, get the value from the database for the path "users/<userId>/type". Then use a switch statement to redirect to the correct view controller.
Here's the full code
// Sign in to Firebase
FIRAuth.auth()?.signIn(withEmail: "[email protected]", password: "Password123", completion: {
(user, error) in
// If there's no errors
if error == nil {
// Get the type from the database. It's path is users/<userId>/type.
// Notice "observeSingleEvent", so we don't register for getting an update every time it changes.
FIRDatabase.database().reference().child("users/\(user!.uid)/type").observeSingleEvent(of: .value, with: {
(snapshot) in
switch snapshot.value as! String {
// If our user is admin...
case "admin":
// ...redirect to the admin page
let vc = self.storyboard?.instantiateViewController(withIdentifier: "adminVC")
self.present(vc!, animated: true, completion: nil)
// If out user is a regular user...
case "user":
// ...redirect to the user page
let vc = self.storyboard?.instantiateViewController(withIdentifier: "userVC")
self.present(vc!, animated: true, completion: nil)
// If the type wasn't found...
default:
// ...print an error
print("Error: Couldn't find type for user \(user!.uid)")
}
})
}
})
Instead of the whole switch statement you can do
let vc = self.storyboard?.instantiateViewController(withIdentifier: "\(snapshot.value)_View")
self.present(vc!, animated: true, completion: nil)
Warning! This will crash if the type isn't found. But that's fixable :)
Upvotes: 3