遍历Firebase数据库中的用户

时间:2018-11-16 21:15:20

标签: ios iphone swift firebase firebase-realtime-database

我正在尝试遍历用户的信息,然后将其保存在对象中。

这是我的数据

    {
  "users" : {
    "ApC2wS444YbEEUt5BOpFjkn7YTD3" : {
      "UserInfo" : {
        "lat" : 123123,
        "long" : 0,
        "petAge" : 5,
        "petNeme" : "zhshs"
      }
    },
    "doRJjseSogNJrCQ55zMGlJwj6jh2" : {
      "UserInfo" : {
        "UID" : "doRJjseSogNJrCQ55zMGlJwj6jh2",
        "lat" : 0,
        "long" : 0,
        "petAge" : 5,
        "petName" : "BBB"
      }
    }
  }
}

我的代码就是这样

ref = Database.database().reference()
tableView.delegate = self
tableView.dataSource = self

let userID = Auth.auth().currentUser?.uid
ref = Database.database().reference()

self.ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
    // Get user value

    for child in snapshot.children.allObjects as! [DataSnapshot] {

        print(child.value)

        let value = snapshot.value as! NSDictionary
        let userInfo = value[0] as! NSDictionary
        let UID = userInfo["UID"] as! String
        let lat = userInfo["lat"] as! Double
        let long = userInfo["long"] as! Double
        let name = userInfo["petName"] as! String ?? ""
        let age = userInfo["petAge"] as! Double
    }

}) { (error) in
    print(error.localizedDescription)
}

我不太了解如何处理快照以及如何正确获取数据

我能够获取单个节点,但是当我尝试传递迭代时,每次迭代都会使我回到同一个节点

有帮助吗?

1 个答案:

答案 0 :(得分:0)

在您的示例中,您在for循环中使用了此let userInfo = value[0] as! NSDictionary,此循环后来仅为您提供第一个节点:[0]

另外,让我向您展示我从快照中检索数据的示例(在我的情况下,我的卡具有autoId):

func loadDataFromDb(completion: @escaping ([Card])->()) {
        var cards: [Card] = []
        let userRef = getCurrentUserRef()
        usersRef.child(userRef).child(Paths.cards).observeSingleEvent(of: .value) { (snapshot) in
            for child in snapshot.children {
                if let snapshot = child as? DataSnapshot,
                    let card = Card(snapshot: snapshot) {
                    cards.append(card)
                }
            }
            completion(cards)
        }
    }

我在failable init中也有Card

private enum Constants {
    static let name = "name"
    static let barcode = "barcode"
}

final class Card {
    let name: String
    let barcode: String

    init(_ name: String, barcode: String) {
        self.name = name
        self.barcode = barcode
    }

    init?(snapshot: DataSnapshot) {
        guard let value = snapshot.value as? [String : AnyObject],
        let name = value[Constants.name] as? String,
        let barcode = value[Constants.barcode] as? String else {
            return nil
        }
        self.name = name
        self.barcode = barcode
    }
}