Firebase:从实时数据库中检索childByAutoID

时间:2016-09-05 10:10:48

标签: ios swift firebase firebase-realtime-database

我目前正在学习Firebase和iOS的绳索,所以请耐心等待。我目前在我的桌子上发帖名为Posts,如下所示:

 let postInfo = ["Description": txtPostDescription.text!, "ImageUrl": imgUrl, "Likes": 0]

 var t = FIRDatabase.database().reference().child("Posts").childByAutoId().setValue(postInfo)

 print(t)

我尝试检索插入新记录时创建的primary key,但是我无法检索它。我已经尝试了childByAutoId()但由于浏览网页而无法找到可靠的解决方案,这是随机猜测)。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

let postInfo = ["Description": txtPostDescription.text!, "ImageUrl": imgUrl, "Likes": 0]

var reference  = FIRDatabase.database().reference().child("Posts").childByAutoId()

reference.setValue(postInfo)
let childautoID = reference.key 
print(childautoID)

注意: - Althogh childByAutoId()是来自Firebase的强大功能。但是当您想要创建一个节点时,更喜欢timestamps存储数据我喜欢时间戳的原因是因为它们也可以帮助分类数据......但那只是我...

替代方案: -

let timeStamp = Int(NSDate.timeIntervalSinceReferenceDate()*1000) //Will give you a unique id every second or even millisecond if you want.. 
FIRDatabase.database().reference().child("Posts").child(timeStamp).setValue(postInfo)