Reading data from firebase (ios) - ios

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.

Related

Unable to node specific values in firebase using swift 3

I am able to fetch all users but I want need user ID specific data.
For example you can see here are lots of users are registered but I need details only for 3 nodes:
323QGP6qryTWs7EnnXRX1stgocP2
iy5ssz0ALphtgViALEOG0N4TeGd2
OlA0rhAVfsNvixe8KEsUmdCfuN42
Please help to get these records.
Thanks.
let ref = Database.database().reference().child("users").observeSingleEvent(of: .value, with : { snapshot in {
if snapshot is NSNull{
//handles errors
}
else{
let dict = snapshot.value as? NSDictionary{
let firstDict = dict["323QGP6qryTWs7EnnXRX1stgocP2"] as? NSDictionary
let secondDict = dict["iy5ssz0ALphtgViALEOG0N4TeGd2"] as? NSDictionary
let thirdDict = dict["OlA0rhAVfsNvixe8KEsUmdCfuN42"] as? NSDictionary
//Then to gather whichever node you want inside these users:
let requestedNode = THEDICTIONARYYOUARELOOKINGAT["THE_NAME_OF_THE_NODE"] as? String //String, Int, Dictionary, array, boolean, ect.
}
}
})

How to read data from FireBase

I have problem reading from Firebase in Swift.
Here is my Firebase database:
and here is my code:
var ref: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
NSLog("Reading from DB")
ref = FIRDatabase.database().reference()
self.ref?.child("Frais").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? [String: Int]
var frpx1 = (value?["frpx1"]!)!
var frpx10 = (value?["frpx10"]!)!
var frpx11 = (value?["frpx11"]!)!
var frpx12 = (value?["frpx12"]!)!
var frpx13 = (value?["frpx13"]!)!
var frpx14 = (value?["frpx14"]!)!
var frpx15 = (value?["frpx15"]!)!
var frpx16 = (value?["frpx16"]!)!
})
print(frpx1)
print(frpx10)
print(frpx11)
print(frpx12)
print(frpx13)
print(frpx14)
print(frpx15)
print(frpx16)
}
I did not find the problem.
I do not have the data from database in frpx1, ..., frpx16.
Your code have a couple of minor issues:
you are casting the returned value to [String: Int] when you should be using [String: Any] instead since not all values are String based.
you are printing the results outside the completion handler. You need to wait the handler to be called to then read the results (i.e., when the method observeSingleEvent returns Firebase is still processing your request).
Fixing both issues should get you going:
...
self.ref?.child("Frais").observeSingleEvent(of: .value, with: {
(snapshot) in
guard let value = snapshot.value as? [String: Any] else {
print("Snapshot type mismatch: \(snapshot.key)")
return
}
let frpx1 = value["frpx1"]
let frpx10 = value["frpx10"]
let frpx11 = value["frpx11"]
...
print(frpx1)
print(frpx10)
print(frpx11)
...
})
PS. I also improved your coding style a little to help prevent further issues ;)

Nested Firebase data for TableView

I'm having a little trouble accessing and saving nested Firebase data.
Here is how my database is set up:
How would I get Bike and Popsicle into an array as well as getting country and price in 2 other arrays? I will be using these arrays to populate a TableView.
Try something like this:
let ref = FIRDatabase.database().reference().child("Test")
ref.observeSingleEvent(of: .value, with: { snapshot in
if let data = snapshot.value as? [String : [String : NSNumber]] {
let bikePopsicleArray = Array(data.keys)
let countryArray = [String]()
let pricesArray = [NSNumber]()
for (key, value) in data.values {
countryArray.append(key)
pricesArray.append(value)
}
}
})
Not sure if this will work but give it a try, let me know how it goes.

Unable to get keys from firebase database

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);
})
});

how to retrieve child(array) inside another firebase child

I am trying to print array from the firebase. Actually if we tap a medication in a list(tableviewcontroller), it will show its specfic dosages. I got stucked to retrieve the dosages list. Here is my code to get data from firebase. Any help is appreciated. Thanks in advance. My firebase structure looks like this.. firebase img
func loadDataFromFirebase() {
databaseRef = FIRDatabase.database().reference().child("medication")
databaseRef.observeEventType(.Value, withBlock: { snapshot in
for item in snapshot.children{
FIRDatabase.database().reference().child("medication").child("options").observeEventType(.Value, withBlock: {snapshot in
print(snapshot.value)
})
}
})
You should take a look on firebase documentation https://firebase.google.com/docs/database/ios/read-and-write
but if I'm understanding your idea, you probably has a model class for your medications. So, to retrieve your data you should do like this for Swift 3.0:
func loadDataFromFirebase() {
databaseRef = FIRDatabase.database().reference().child("medication")
databaseRef.observe(.value, with: { (snapshot) in
for item in snapshot.children{
// here you have the objects that contains your medications
let value = item.value as? NSDictionary
let name = value?["name"] as? String ?? ""
let dossage = value?["dossage"] as? String ?? ""
let type = value?["type"] as? String ?? ""
let options = value?["options"] as? [String] ?? ""
let medication = Medication(name: name, dossage: dossage, type: type, options: options)
// now you populate your medications array
yourArrayOfMedications.append(medication)
}
yourTableView.reloadData()
})
}
Now that you have your array with all your medications, you just need to populate your tableView with this medications. When someone press an item on table you can just call prepareForSegue: and send your yourArrayOfMedications[indexPath.row].options to the next view
The solution is same as above but with a small change.
func loadDataFromFirebase() {
databaseRef = FIRDatabase.database().reference().child("medication")
databaseRef.observe(.value, with: { (snapshot) in
for item in snapshot.children{
// here you have the objects that contains your medications
let value = item.value as? NSDictionary
let name = value?["name"] as? String ?? ""
let dossage = value?["dossage"] as? String ?? ""
let type = value?["type"] as? String ?? ""
let options = value?["options"] as? [String : String] ?? [:]
print(options["first"]) // -> this will print 100 as per your image
// Similarly you can add do whatever you want with this data
let medication = Medication(name: name, dossage: dossage, type: type, options: options)
// now you populate your medications array
yourArrayOfMedications.append(medication)
}
yourTableView.reloadData()
})
}

Resources