如何使用firebase和Xcode将不同的用户发送到单独的视图控制器

时间:2016-12-31 08:17:03

标签: ios swift firebase firebase-authentication

我对编码很新,并且开始使用firebase作为我在Xcode中使用swift创建的应用程序的后端服务器。

应用程序本身将有一个登录页面,但有3种不同类型的用户。管理员将拥有与其他2个用户不同的权限。

我目前的代码是:

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)                
    }

代码正在获取身份验证页面的电子邮件和密码。但由于3种不同类型的用户,我不希望他们都进入“管理员”行列。查看控制器。

有没有办法让其他2个用户使用这种身份验证方法转到他们自己的视图控制器?

1 个答案:

答案 0 :(得分:3)

如果要为用户存储类型,则必须使用数据库。像这样 enter image description here

当用户登录时,从数据库中获取路径“users /< userId> / type”的值。然后使用switch语句重定向到正确的视图控制器。

这是完整的代码

var result = from course in DbCourses
             left join courseTutionCenter in DbCourseTutionCenter
             on course.Id equals courseTutionCenter.CourseId 
             left join courseStudent in DbCourseStudent
             on courseStudent.Course_TutionCenter_Id equals courseTutionCenter.TutionCenterId  
             group by new { course.Id, course.Name } into gr
             select new
             {
                 CourseId = gr.Key.Id,
                 CourseName = gr.Key.Name,
                 TutionCenters = gr.GroupBy(x=>x.courseStudent.Course_TutionCenter_Id).Count(),
                 Students = gr.GroupBy(x=>x.courseStudent.Id).Count()
             };

而不是整个switch语句,你可以做

 // Sign in to Firebase
 FIRAuth.auth()?.signIn(withEmail: "ntoonio@gmail.com", 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)")
                 }
            })
        }
    })

警告!如果找不到类型,这将崩溃。但这是可以解决的:)