【问题标题】:Firebase Retrieving Data in SwiftFirebase 在 Swift 中检索数据
【发布时间】:2016-06-11 03:23:43
【问题描述】:

我正在尝试仅从当前登录的用户中检索特定数据。我的数据库中的数据如下所示:

例如,我只想获取 full_name 并将其保存在变量 userName 中。以下是我用来获取数据的方法

ref.queryOrderedByChild("full_name").queryEqualToValue("userIdentifier").observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
            print(snapshot.value)
            // let userName = snapshot.value["full_name"] as! String
        })

不幸的是,这是我的控制台打印的。

如果有任何帮助,我将不胜感激 :) 谢谢!

【问题讨论】:

  • 嘿蒂姆。你在做身份验证吗?你是干什么用的?
  • 我正在尝试将数据保存到局部变量中,以便我可以使用它来显示内容:-)

标签: ios swift firebase


【解决方案1】:

它会为您提供警告消息indexOn,因为您正在执行查询。

你应该通过 .indexOn 定义你将被索引的键 安全和 Firebase 规则中的规则。虽然你被允许 在客户端上临时创建这些查询,你会看到很多 提高使用 .indexOn 时的性能

如果您知道要查找的名称,您可以直接转到该节点,无需查询。

    let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("stephenwarren001@yahoo.com")

    // only need to fetch once so use single event

    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in

        if !snapshot.exists() { return }

        //print(snapshot)

        if let userName = snapshot.value["full_name"] as? String {
            print(userName)
        }
        if let email = snapshot.value["email"] as? String {
            print(email)
        }

        // can also use
        // snapshot.childSnapshotForPath("full_name").value as! String
    })

【讨论】:

  • xcode 建议我添加一个“!”在价值之后我不确定我们应该做什么......事实上这可能是导致它崩溃的原因(?)
  • 它是一个可选的强制解包 - 如果该值不存在,它将崩溃。
  • 另外,根据您的模型设计,您可能会返回多个快照。因此,您将使用 snapshot.children 并遍历它们。本教程非常适合这些基础知识raywenderlich.com/109706/firebase-tutorial-getting-started - firebase 入门指南也非常非常好! firebase.google.com/docs/ios/setup
  • 我应该强制拆开它吗?我怀疑我不应该是因为每个人都在没有“!”的情况下写它。除非我强制展开值,否则 Xcode 不会构建
  • 我将创建一个结构,即 Person - 传入快照,然后处理快照中的信息。按照编译器的建议让它运行。如果您知道它不会为零,则强制展开是可以的。
【解决方案2】:

斯威夫特 4

let ref = Database.database().reference(withPath: "user")
    ref.observeSingleEvent(of: .value, with: { snapshot in

        if !snapshot.exists() { return }

        print(snapshot) // Its print all values including Snap (User)

        print(snapshot.value!)

        let username = snapshot.childSnapshot(forPath: "full_name").value
        print(username!)

    })

【讨论】:

  • 在当前版本中应该看起来像这样 let ref = Database.database().reference() let userID = Auth.auth().currentUser?.uid ref.child("Users") .child(userID ?? "").observeSingleEvent(of: .value, with: { (snapshot) in })
【解决方案3】:
{
    "rules": {
         "tbl_name": {
            ".indexOn": ["field_name1", "field_name2"]
         },
    ".read": true,
    ".write": true
    }
}

您可以在任何字段上应用 indexOn。在规则安全和规则选项卡中添加此 json。 希望这对你有用。 :)

【讨论】:

    【解决方案4】:

    它检索登录的用户数据:

    let ref = FIRDatabase.database().reference(fromURL: "DATABASE_URl")
    let userID = FIRAuth.auth()?.currentUser?.uid
    let usersRef = ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
    print(snapshot)
    

    【讨论】:

      【解决方案5】:
      let ref = Database.database().reference().child("users/stephenwarren001@yahoo.com")
      
      
          ref.observeSingleEvent(of: .value, with: { (snap : DataSnapshot)  in
      
              print("\(String(describing:  snap.value))")
      
      
          }) { (err: Error) in
      
      
              print("\(err.localizedDescription)")
      
          }
      

      【讨论】:

      • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
      【解决方案6】:
          var refDatabase = DatabaseReference()
      
          refDatabase = Database.database().reference().child("users");
       let refUserIdChild = refDatabase.child("stephenwarren001@yahoo.com")
                          
                          refUserIdChild.observeSingleEvent(of: .value, with: { snapshot in
      
                              if !snapshot.exists() { return }
      
                              print(snapshot) // Its print all values including Snap (User)
      
                              print(snapshot.value!)
                              
      
                          if let tempDic : Dictionary = snapshot.value as? Dictionary<String,Any>
                          {
                                 
                                  if let userName = tempDic["full_name"] as? String {
                                        self.tfName.text = userName
      
                                    }
      
                                  if let email = tempDic["email"] as? String {
                                          self.tfEmail.text  = email
      
                                    }
      
                                 
                          }
      
      
                          })
                          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-31
        • 2018-01-05
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        相关资源
        最近更新 更多