Reputation: 3858
I have a list of data to retrieve from Firebase, using Swift.
I tried to get the data using .Value
and Firebase returns a dictionary with the IDs of each item and for each ID the info associated.
The endpoint I am calling is /ideas.
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
In order to optimize this, I changed with .ChildAdded
. In this case I get only the single item without the ID associated.
Is it possible to get also the ID of each item using .ChildAdded
?
If not, how can I save the ID generated by Firebase into each item? Currently I am saving each item in this way:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS).childByAutoId()
let idea = [
IdeaStructure.FIELD_MESSAGE: message,
IdeaStructure.FIELD_CREATOR_ID: userId,
IdeaStructure.FIELD_CREATION_DATE: NSDate().formattedISO8601
]
ideasRef.setValue(idea)
Upvotes: 0
Views: 475
Reputation: 599766
To get the key of the snapshot, access its key
property:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.key)
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
This and many more topics are covered in Firebase's excellent programming guide for iOS.
Upvotes: 3