How to read Firebase child value? - ios

I'm a newbie to coding and Swift.
I'm trying to retrieve the value of house1Colour from my Firebase database in my app. I've tried these methods so far.
let eg = FIRDatabase.database().reference(withPath: "test")
(when I use this I get a THREAD 1 Signal SIGABRT error, I'm not sure why)
and:
var test:String!
FIRDatabase.database().reference().child("house1Colour").observeSingleEvent(of: .value, with: {(snap) in
if let snapDict = snap.value as? Dictionary <String, AnyObject>{
self.test = snapDict["house1Colour"] as! String
print(self.test)
}
})
None of them work.

The value of FIRDatabase.database().reference().child("house1Colour") is just the string since you already specified the key house1Colour.
Therefore you should be able to just:
if let snapString = snap.value as? String {
print(snapString)
}

Related

Reading data from firebase (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.

Swift Retrieve Firebase Data from Database

I'm trying to retrieve data from Firebase but I'm having issues.
let refEmployees = Database.database().reference(withPath: "Employees")
refEmployees.child("Logan").observeSingleEvent(of: .value, with: {
snapshot in
let shift = snapshot.value as? String
self.shifts.append(shift!)
self.workSchedule.reloadData()
})
That is my code, my database looks like this.
When I run it, I get
fatal error: unexpectedly found nil while unwrapping an Optional value
Any ideas? I'm stumped. I also can add information to the database at the same time and change to childAdded and the information loads properly.
Usually I never try to get the reference "withPath", but by child.
I would Try to do it like this:
let ref = Database.database().reference().child("Employees").child("Logan")
On the other part, is a bad practice to force unwrap optionals that you don't know you are actually going to get, I would change the closure to:
ref.observeSingleEvent(of: .value, with: {
snapshot in
guard let shift = snapshot.value as? String else {
print("Value is Nil or not String")
return
}
self.shifts.append(shift)
self.workSchedule.reloadData()
})
Like someone in the comments said, may be a good idea to print the optional value first to see if you are actually getting the value that you need from the database.
Hope this helps
let refEmployees = Data`base.database().reference()
refEmployees,child("Employees").child("Logan").observeSingleEvent(of: .value, with: {
snapshot in
let shift = snapshot.value! as! [String : AnyObject]
let dictKeys = [String](snapshot.keys)
//Will give you all` keys from DB 0,1,2,3,4,5,6
let dictValues = [AnyObject](snapshot.values)
//will give you` all values "off", "off", "2-10"..."off"
//use keys or values append in array if you want as I could not understand what you are trying to save in self.shifts
self.shifts.append(shift!)
self.workSchedule.reloadData()
})

Firebase iOS Swift retrive list of favourites with data from other node

Pictures
-pictureID
-- name
-- date
Like
-pictureID
-- userID: true
-- userID: true
likePerUser
-userID
--pictureID: true
--pictureID: true
Users
-userID
-- name
-- lastname
I would like to retrieve all picture that current user has liked.
I did:
ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snap) in
for item1 in snap.children{
let firstItem1 = (snap: item1 as! FIRDataSnapshot)
print("key favourites\(firstItem1.key)")
let firstId = firstItem1.key
self.ref.child("pictures").child(firstId).observeSingleEvent(of: .value, with: { (snapshot) in
for item in snapshot.children{
let firstItem = (snapshot: item as! FIRDataSnapshot)
print("key pictures \(firstItem.key)")
let dict = firstItem.value as! [String: Any
let name = dict["name"] as! String
print(name)
}
Even, If it seems that firstId has the right value each time,
I always get an error:
Could not cast value of type '__NSCFBoolean' (0x110dae5b8) to
'NSDictionary' (0x110daf288).
Please help....
I solved doing this:
if let dictionary = snapshot.value as? NSDictionary {
if let name = dictionary["nome"] as? String {
print(name)
}
}
This questions helped me: Swift - Could not cast value of type '__NSCFString' to 'NSDictionary'
Also i didn't need to iterate once more.
let dict = firstItem.value as! [String: Any
Here is where you attempt to cast a value as a dictionary. It's unclear whether the value is a dictionary based upon the model of the database you've shared. But there's a good chance that if you print firstItem.value.debugDescription, you will see that the value it isn't a dictionary object.

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 objects from firebase by key value

I'm new to firebase and I have such structure of my firebase project
I want to get all objects, that "Interested" value is equal to "men"
I wrote such code, to get all object sorted by interes value:
let thisUserRef = URL_BASE.childByAppendingPath("profile")
thisUserRef.queryOrderedByChild("Interest")
.observeEventType(.Value, withBlock: { snapshot in
if let UserInterest = snapshot.value!["Interest"] as? String {
print (snapshot.key)
}
}
But I receive nil.
you need to loop through all the key-value profiles
if let allProfiles = snapshot.value as? [String:AnyObject] {
for (_,profile) in allProfiles {
print(profile);
let userInterest = profile["Interest"]
}
}
Here _ is the key that is in the format KYXA-random string and profile will be the element for that key.
Edit:
There is querying for child values as per the docs.
Try thisUserRef.queryOrderedByChild("Interest").equalTo("men") and then using the inner loop that i specified in the answer
This is a basic query in Firebase. (Updated for Swift 3, Firebase 4)
let profileRef = self.ref.child("profile")
profileRef.queryOrdered(byChild: "Interest").queryEqual(toValue: "men")
profileRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let dict = child as! [String: Any]
let name = dict["Name"] as! String
print(name)
}
})
The legacy documentation from Firebase really outlines how to work with queries: find it here
Legacy Firebase Queries
The new documentation is pretty thin.
Oh, just to point out the variable; thisUserNode should probably be profileRef as that's what you are actually query'ing.

Resources