Firebase:从实时数据库中检索childByAutoID [英] Firebase : Retrieve childByAutoID from Realtime Database

查看:75
本文介绍了Firebase:从实时数据库中检索childByAutoID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently learning the ropes of Firebase and iOS so please bear with me. I'm currently posting to my table called Posts as shown here:

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

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

 print(t)

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

I'm trying to retrieve the primary key that gets created when I insert the new record, however I'm unable to retrieve it. I've tried childByAutoId() (but that was a random guess due to browsing the web and not being able to find a solid solution). Any ideas?

推荐答案

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 的强大功能。但是,当您想要创建一个具有唯一键的节点时,更喜欢时间戳来存储数据。我更喜欢时间戳的原因是因为它们也可以帮助排序数据......但那就是我..

Note :- Althogh childByAutoId() is a great functionality from Firebase.But prefer timestamps to store the data into when you want to create a node with a unique key.The reason why i prefer timestamps is because they can also be helpful in sorting of data...But thats just me..

备选方案: -

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)

这篇关于Firebase:从实时数据库中检索childByAutoID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆