I am a beginner. The main function is that when user click a each button of cell, it will update data. But I just write a new data, it cannot update existing data.
ViewController.swift
This function write's a new key is not save existing key. How can I solve?
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("location").queryOrderedByKey().observe(.childAdded, with: {snapshot in
guard let firebaseResponse = snapshot.value as? [String:Any] else
{
print("Snapshot is nil hence no data returned")
return
}
let status = firebaseResponse["status"] as! Int
let key = databaseRef.childByAutoId().key
let up = ["id":key,
"status":status] as [String : Any]
databaseRef.child("location").child(key).setValue(up)
self.posts.insert(postStruct(status:status,key:key), at: 0)
self.tableView.reloadData()
})
This my Exercise xcode in google drive
https://drive.google.com/open?id=0B2jj6V1tOGcVTm9JSy1uNV9fZnM
This is firebase data for image:
Problem is in this line
let key = databaseRef.childByAutoId().key
You are creating new autoID instead of using the current child autoId from snapshot.key, so change that line with below one and you all set to go.
let key = snapshot.key
Related
I have 2 records in my users table
This code below
let fcmTokenRef = Database.database().reference().root.child("users").child(id!).child("fcmToken")
fcmTokenRef.observe(DataEventType.value, with: { (snapshot) in
print(">>",snapshot)
})
will print out the token of a child
How do I adjust my code to print all the tokens for all my children?
You can try
let fcmTokenRef = Database.database().reference().root.child("users").observe(DataEventType.value, with: { (snapshot) in
print(">>",snapshot)
let dic = snapshot.value as! [String:[String:Any]]
Array(dic.values).forEach {
let str = $0["fcmToken"] as! String
print(str)
}
})
You’re requesting a onetime read, hence you’re reading the data once. You need to use .childAdded
Try this:
let fcmTokenRef = Database.database().reference().child(“users”)
fcmTokenRef.observe(.childAdded, with: { (snapshot) in
print(">>",snapshot)
guard let data = snapshot as? NSDictionary else {return}
var each_token = data[“fcmToken”] as? String
print(“all tokens: \(each_token!)”)
})
#puf says something very important:
differences between child added and value firebase
The child_added event fires for each matching child under the node that you query. If there are no matching children, it will not fire.
I have an app where I have a list of data that I manually enter into Firebase. Here is an image of the Firebase Database:
When the user selects an index row, it goes into another view controller. Inside that view controller there is a tableview, which I want to populate with the data from the “name” that I selected.
For example, if I select the “name” from [acct0], I want the “name” and “genre” to also appear in the new tableview.
Currently, I am trying to print the data based on the selection in the previous view controller.
let user = User()
ref?.child("FeaturedAccounts/AccountNames").child(user.name!).observeSingleEvent(of: .value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
let genre = userDict["genre"] as! String
print("Genre: \(genre)")
print(user.name!)
})
Your query looks correct to me. It's hard to say exactly what is going wrong without more information. Here is some code you can use to help debug your issue. If you post some more of your code or explain exactly what is currently happening with your query I can help more.
let user = User()
let ref = Database.database().reference()
ref.child("FeaturedAccounts").child("AccountNames").child(user.name!).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
print(snapshot.value)
}
else {
print("Query returned no data")
}
if let userDict = snapshot.value as? [String: AnyObject] {
if let genre = userDict["genre"] as? String {
print("Genre: \(genre)")
}
else {
print("could not cast genre to string")
}
}
else {
print("Could not cast userDict")
}
})
This is my first screenshot database in firebase:
This is my second screenshot database in firebase:
I am able to retrieve data from firebase also set in table view. But I want all data that which first screenshot database key (1album) equal to second database post_key: 1album.
I tried like this:
refhandel = ref.child("SongPlay").child("1album"] ).queryOrdered(byChild:"post_key").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? [String: AnyObject]{
let music = MusicDataModel()
music.setValuesForKeys(item)
MusicData.append(music)
}
})
after read firebase documentation, I got my Answer where i made mistake.
here what i was done. i just replace queryEqual instance of child
refhandel = ref.child("SongPlay").queryOrdered(byChild:"post_key").queryEqual(toValue: post_key[myIndex]).observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? [String: AnyObject]{
let music = MusicDataModel()
music.setValuesForKeys(item)
MusicData.append(music)
}
})
I have a small dataset in Firebase database, but unfortunately, I can't get read value from list correctly. Here is the structure of the database.
I just need to get the value of day and reference it to var. Thanks in advance.
var collnum = ""
ref = Database.database().reference()
let collid = ref.child("collid").child("day")
collid.observeSingleEvent(of : .value, with : {(Snapshot) in
print(Snapshot)
if let snapDate = Snapshot.value as? String{
collnum = snapDate
print(snapDate)
}
})
let database = FIRDatabase.database().reference()
database.child("collid").queryOrderedByKey().observe(.value, with:
{
if let value = snapshot.value as? [String: AnyObject]
{
let ui = value["day"] as! String
print(ui)
}
}
You can do something like this to read the data. This will read the data from the database and put into an array, allowing you to read the data.
I have been pondering for the longest time in my student programmer life. I would like to know
I added the keys using autoChildId.
How to get keys from firebase database swift 2? I know how to get from Android using .getKeys()
My best friend, Google, taught me to use allKeys. However, my friendship is on the verge of in despair right now as I received the following msg that our relationship with .allKeys will always fail ( see image below). Haish...
I need this in order to show the data from Firebase Database into my tableview cos I believe this is the issue to a empty table just like how my heart is for my project. No heart.
Here is how my firebase database looks like:
Here is my code:
func findPlaceToEat(){
print("inside findPlaceToEat()")
print("Plan price level")
print(planPriceLevel)
print("End of price level")
ref = FIRDatabase.database().reference()
ref.child("places_detail").child("price_level").child(planPriceLevel).observeEventType(.ChildAdded, withBlock:{
(snapshot) in
if let dictionary = snapshot.value?.allKeys! as? [String: AnyObject]{
let PlaceObj = placeObj(place_name: dictionary["place_name"] as! String, place_type: dictionary["place_type"] as! String, price_range: dictionary["price_range"] as! String, vegan_type:dictionary["vegan_type"] as! String , website: dictionary["website"] as! String)
print("Whatever")
print(PlaceObj);
//self.tableView.reloadData()
}
}, withCancelBlock: nil)
}
to get key from snapshot
snapshot.key
I got a workaround for my project, everyone please pray that my lecturer don't see this. :
What I did was inside the save button I retrieve the value from database and then save it back into Firebase Database.
ref = FIRDatabase.database().reference()
ref.child("hello").child("google! I need a part time job").child(planPriceLevel).observeEventType(FIRDataEventType.ChildAdded, withBlock:{
(snapshot: FIRDataSnapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
let getPlaceObj = placeObj()
getPlaceObj.setValuesForKeysWithDictionary(dictionary)
self.PlaceObj.append(getPlaceObj)
print("Name " ,getPlaceObj.place_name)
}
let place_name = snapshot.value?.objectForKey("place_name") as! String
let place_type = snapshot.value?.objectForKey("place_type") as! String
let price_range = snapshot.value?.objectForKey("price_range") as! String
let vegan_type = snapshot.value?.objectForKey("vegan_type") as! String
let website = snapshot.value?.objectForKey("website") as! String
print(place_name, place_type, price_range, vegan_type, website)
let savePlan : [String: AnyObject] = ["place_name":place_name, "place_type":place_type, "price_range":price_range, "vegan_type":vegan_type, "website":website]
self.ref.child("can you place hire me as your intern? I am from Singapore!!!").child(self.user!.uid).childByAutoId().setValue(savePlan)
}, withCancelBlock: nil)
You need to define query orderbykey like bellow:
this.afd.list('/yourItems/', {query:{orderByKey :true}}).subscribe((elements) => {
elements.map(element=>{
console.log(element.$key);
})
});