5

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)

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?

Dravidian
  • 9,945
  • 3
  • 34
  • 74
Code Ratchet
  • 5,758
  • 18
  • 77
  • 141

1 Answers1

15
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)

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..

Alternative :-

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)
Dravidian
  • 9,945
  • 3
  • 34
  • 74
  • Working, Thanks @Dravidian – Code Ratchet Sep 05 '16 at 10:34
  • Thanks @Dravidian – Vinoth Vino Aug 03 '17 at 11:03
  • 3
    Note that childByAutoId() *does* return a time-sortable ID: "The unique key generated by childByAutoId: is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted." https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DatabaseReference – Justin Fyles Jul 10 '18 at 16:41