ios - 在 firebase 中使用 Snap 值

标签 ios swift firebase firebase-realtime-database firebase-authentication

这是我的 iOS 应用程序的情况(我使用的是 swift 3.0 和 firebase)。

我有一个登录屏幕,用户可以使用 firebase 的身份验证通过电子邮件登录。为此,我使用以下代码:

    @IBAction func signInButtonPressed(_ sender: UIButton)
{


    if let email = emailField.text, let password = passwordField.text
    {
      //  FIRDatabase.database().reference().child("users").child(self.emailField.text!).observeSingleEvent(of: .value, with: {(userEmail) in
       // FIRAuth.auth()?.signIn(withEmail: email, password: password)

        FIRAuth.auth()?.signIn(withEmail: email, password: password)
        {
            (user, error) in

            if let error = error
            {
                let alertController = UIAlertController(title: "Login or password incorrect", message:
                    "", preferredStyle: UIAlertControllerStyle.alert)
                alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil))

                self.present(alertController, animated: true, completion: nil)                }
            else
            {
                print("AUTH: EMAIL AUTH SUCCESSFUL")

                User.currentUserId = user?.uid
                User.startTrackingCurrentUser()
                self.performSegue(withIdentifier: "ToFeed", sender: nil)
            }
        }
    }
}

运行完美!

我想要实现的目标是通过用户名登录用户。 为此,我认为最好的办法是在识别用户是否存在时发送电子邮件值 - 从数据库获取数据。

我的数据库配置正确,并获取身份验证系统,例如:

--name of db
----posts
----users
------username
------email
------id

当我在文本字段中输入正确的用户名时,我可以让用户在控制台中识别:

@IBAction func textFieldEditingDidChange(_ sender: Any) {
    FIRDatabase.database().reference().child("users").child(self.emailField.text!).observeSingleEvent(of: .value, with: {(email) in

    if let userDict = email.value as? [String:AnyObject]{
        for each in userDict{
            let email = each.1 as! String
        }
    }

    if email.exists(){

        print(email)

    }else{

        print("USER NOT EXIST")

    }

})

}

当写入的用户名正确时,我会在控制台中显示以下内容:

Snap (myuser) {
username = myuser;
email = "myemail@email.com";
id = 8mbwXUMe0Ye4ip2mhhvEySxmxiI5;

}

为此,我一直在关注这个线程:

Sign In by UserName : Firebase,Swift

从现在开始,我如何在提交时使用快照中的电子邮件值而不是用户名来登录?我没能成功,我已经为此工作了一个星期了。 。 .

任何帮助都会很棒!我开始从事 iOS 开发。

非常感谢!

---编辑--

现在我设法仅通过以下方式在我的控制台中尝试打印电子邮件:

IBAction func textFieldEditingDidChange(_ sender: Any) {


    FIRDatabase.database().reference().child("users").child(self.emailField.text!).observeSingleEvent(of: .value, with: {(email) in

        if let userDict = email.value as? [String:AnyObject]{
   print(email)

        }

        if email.exists(){


        }else{

            print("USER NOT EXIST")

        }

    })
}

但仍在寻找如何传递值?

最佳答案

我想强调的是,强烈建议不要创建用户名登录系统!

让我们从用户节点开始

user_email_lookup
  uid_0
    email: "johnny@dontdothis.com"
    user_name: "johnny_unsecure"
  uid_1
    email: "fred@exposednodes.com"
    user_name: "fred_stolendata"

user_email_lookup 节点将提供用户输入的用户名与 Firebase 中经过身份验证的用户的电子邮件地址之间的链接。该节点需要有允许任何人访问它的规则 - 这是必要的,因为该节点上的查询需要由未经身份验证的用户完成。还有另一种结构选项

user_email_lookup
  johnny_unsecure: "johnny@dontdothis.com"
  fred_stolendata: "fred@exposednodes.com"

但这会使以后管理用户名和/或电子邮件更改变得更加困难,因此不推荐。

(再次强调,不要这样做,这是不好的形式)

以下是需要应用 user_email_lookup 的基本规则

{
    "rules": {
        ".read": true,
        ".write": true
    }
}

(呃;记住这个节点可以被任何人访问。不要这样做!)

假设应用程序显示一个屏幕,用户可以在其中输入用户名和密码,并带有登录按钮。按下登录按钮会调用 beginLogin 函数,如下

func beginLogin() {
    let userName = "johnny_unsecure" //from the userNameField.text
    let password = "my_password" // from the passwordField.text

    let lookupRef = self.ref.child("user_email_lookup")
    let queryRef = lookupRef.queryOrdered(byChild: "user_name").queryEqual(toValue: userName)

    queryRef.observeSingleEvent(of: .childAdded, with: { snapshot in
        let dict = snapshot.value as! [String: Any]
        let email = dict["email"] as! String
        self.logUserIn(email: email, password: password)
    })
}


func logUserIn(email: String, password: String) {

    Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in 
        if error != nil {
            let err = error?.localizedDescription
            print(err)
        } else {
            print("succesfully authd")
            print(user)
        }
    })
}

关于ios - 在 firebase 中使用 Snap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44260730/

相关文章:

ios - 如何在谷歌地图iOS Sdk中拖动圆形 View

ios - 为不同的 iPhone 调整以图像为背景的 UIButton 的大小

java - 为什么插入多个项目后数组列表 ratingItemList 显示为空?

reactjs - {React Native} Async\Await 无法与 setState 正常工作

ios - 检查对象类型失败,出现 "is not a type"错误

ios - 自定义单元格中的不同图像

ios - 无法显示我的 iOS VoIP 应用程序的 onComingCall ViewController

ios - 如何在 jenkins 中获取 XCTAttachments

xcode - 我可以在不同的 UIView 中重复一个标签/按钮/变量名吗? (X代码)

android - Firebase 身份验证与 GoogleAccountCredetial