筛选数据库子项并将每个名称作为字符串返回



我一直在用Firebase Realtime Database(通过CocoaPods(在最新版本的Xcode和Swift中开发一个应用程序,我遇到了一个大问题。我想过滤我的数据库的每个子项,只返回包含"user:cvb"的子项。我找到了一种过滤每个结果的方法,但在此之后,我希望将结果的同级视为字符串(我需要它是字符串,以便我可以以编程方式创建具有此名称的标签(。

前任:

users
  cvb
    events
      // This should be read and name: "abgdeze" returned as a String not Any
      randomChildNameThatIWillNotKnow
        name: "abgdeze"
        users: "cvb"
      thisShouldBeFilteredOut
        name: "irrleveant"
        users: "irrleveant"
let xPos = 100
var yPos = 100
let query = userRef.queryOrdered(byChild: "users").queryEqual(toValue: filters)
query.observe(.value, with: { (snapshot) in
  for childSnapshot in snapshot.children {
    print(childSnapshot as? String ?? "")
    let labelNum = UILabel()
    labelNum.text = childSnapshot as? String
    labelNum.textAlignment = .center
    labelNum.layer.borderWidth = 1.0
    labelNum.layer.borderColor = UIColor.lightGray.cgColor
    let bounds = UIScreen.main.bounds
    let width = bounds.size.width
    let split = "(width / 7)".components(separatedBy: ".")
    let oneSeventh = Int(split[0]) ?? 0
    let oneBox = oneSeventh
    labelNum.frame = CGRect( x: xPos, y: yPos, width: oneBox, height: oneBox)
     self.view.addSubview(labelNum)
     // The Labels display nothing inside and are just blank boxes
     yPos += 100
  }
})


预期:框一个接一个地显示,其中包含 name 元素发生的情况:盒子的位置很好,但空白。

我不确定userRef代码中的哪个节点。我相信它必须引用events节点才能使您的查询正常工作。

let eventsRef = dbRef.child("users").child("cvb").child("events")

获得对events节点的引用后,问题归结为仅从快照中提取数据。 snapshot.children是一个NSEnumerator对象,可用于循环访问快照的所有子对象。事实上,孩子只是另一个DataSnapshot对象。若要从 DataSnapshot 对象中提取数据,请使用属性 value ,这将返回 Any? 。然后,您可以将其强制转换为预期类型(在您的情况下为 [String : String] (。

    let eventsRef = Database.database().reference().child("users").child("cvb").child("events")
    let query = eventsRef.queryOrdered(byChild: "users").queryEqual(toValue: "cvb")
    query.observe(.value, with: { (snapshot) in
        for child in snapshot.children {
            let childSnapshot = child as! DataSnapshot
            let retrievedEvent = childSnapshot.value as! [String: String]
            let name = retrievedEvent["name"]
            let users = retrievedEvent["users"]
            // .. //
        }
    })

最新更新