我现在正在使用firebase,我对此感到困惑。
我有一个如下所示的联系人列表。
我想获得密钥(例如“-L8per5UdCjQyCBxs5Oo”),但我不知道如何做到这一点。
我试过这样的事情:
guard let contactList = self.user?.contactList else { return }
print(contactList[0])
错误信息就是这个。
Cannot subscript a value of type '[String : [String : String]]' with an index of type 'Int'
如何解决此问题? 谢谢。
答案 0 :(得分:1)
var ref:DatabaseReference?
var contactListArray:[DataSnapshot] = [] //you could create an array to save your children
func startListening() {
ref = Database.database().reference().child("contactList")
ref?.observe(.childAdded) {(snapshot) in
self.contactListArray.append(snapshot) // doing this, you can access the first child by contactListArray[0]
// This is how to access info in your snapshot if you need it
let key = snapshot.key //HERE: you'll get the keys
let props = snapshot.value as! Dictionary<String, AnyObject>
let userId = props["userId"] //HERE: how to access to data
}
}
答案 1 :(得分:0)
您可以通过以下方式迭代获取的对象:
for (key, value) in contactList {
///
}
如果你想获得第一个对象,你可以写:
contactList.first