ios - 如何使用 firebase 和 Xcode 将不同的用户发送到单独的 View Controller

标签 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 种不同类型的用户,我不希望他们都进入“AdminVC” View Controller 。

有没有办法让其他 2 个用户使用这种身份验证方法转到他们自己的 View Controller ?

最佳答案

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

当用户登录时,从数据库中获取路径“users//type”的值。然后使用 switch 语句重定向到正确的 View Controller 。

完整代码

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

你可以代替整个 switch 语句

let vc = self.storyboard?.instantiateViewController(withIdentifier: "\(snapshot.value)_View")
self.present(vc!, animated: true, completion: nil)

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

关于ios - 如何使用 firebase 和 Xcode 将不同的用户发送到单独的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406673/

相关文章:

iphone - 将 3 个 UItextfield 中的数据分配到 3 个不同的字符串中

html - 位置:iPhone iOS 中的固定页脚

ios - 使用自定义表格 View 单元格从 UITextField 获取数据

ios - 适用于 iOS 的 FCM 富推送通知负载

ios - 我如何才能检测到用户是否仍然在 firebase 中有一个身份验证 session ?

firebase - firestore sdk 是否使用连接的套接字来发出请求或单独的 http 请求?

ios - 在函数swift中从另一个类调用函数

ios - 了解如何从 IB 初始化自定义 UIView

ios - 向标签添加手势?

ios - 如何在 iOS SDK 中包含第 3 方 SDK