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.
Related
I have places in different cities in my real time database (firebase).
Following is my database structure.
But according to firebase tutorial, I tried following code to get data
cityA.queryOrdered(byChild: "completed").observe(.value, with: { snapShot in
var newItems: [AttractionPlace] = []
for child in snapShot.children {
if let snapShot = child as? DataSnapshot,
let attraction = AttractionPlace(snapShot: snapShot) {
newItems.append(attraction)
}
}
print(newItems.count)
})
I also would like to get data from cityB at the SAME TIME and no idea how to retrieve. I know I can repeat same action to cityB. But is there any better way?
I'm not sure how you want your data structured. Can you show me what an AttractionPlace is supposed to look like? The code below does what you want appending the name of each place to newItems, but without specifying from which city it is. Take notice that I did not use your AttractionPlace object.
let dataref = Database.database().reference()
dataref.child("attractions").observe(.value, with: { (snapshot) in
var newItems = [AnyObject]()
for city in snapshot.children.allObjects as! [DataSnapshot] {
let value = city.value as? NSDictionary ?? [:]
for child in value {
let attraction = child.value
newItems.append(attraction as AnyObject)
}
}
print("newItems: ",newItems)
print("newItems.count: ",newItems.count)
})
Result:
newItems: [Place 3, Place 4, Place 1, Place 2]
newItems.count: 4
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.
}
}
})
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 am completely new to swift and firebase, and I am having difficulties in retrieving array-elements from firebase database
So this is my firebase database
I can retrieve the other elements like this:
database reference
class ViewController: UIViewController {
var ref: FIRDatabaseReference?
let fileName : String = "jsonFile"
method
func parseFirebaseResponse() {
ref?.child("Vandreture").child(fileName).observe(.value, with:
{ (snapshot) in
let dict = snapshot.value as? [String: AnyObject]
let navn = dict!["navn"] as? String
print(navn as Any)
let type = dict!["type"] as? String
print(type as Any)
let Længde = dict!["length"] as? String
print(Længde as Any)
let link = dict!["link"] as? String
print(link as Any)
})
}
the console shows the result
But I have searched for a way to retrieve longitude/latitude pairs,
The first pair should be
latitude 109.987
longitude 102.987
- but so far without luck - help would really be appreciated :)
I think you should restructure your database to something like this:
Vandreture {
jsonFile {
length: "16.2"
link: "www.second.com"
navn: "Kagerup rundt"
positions {
-KqXukxnw3mL38oPeI4y {
x: "102.987"
y: "109.987"
}
-KqXukxnw3mL38oPeI5- {
x: "108.234"
y: "99.098"
}
}
}
}
Then getting your coordinates would be far easier!
Get your "position" as a dictionary (aka [String: AnyObject]).
Then get array of latitude and longitude. Then map of each element from latitude and longitude into a tuple or something like that.
guard let position = dict!["position"] as? [String: AnyObject],
let latitudeArray = position["latitude"] as? [String],
let longitudeArray = position["longitude"] as? [String] else { return }
print(latitudeArray)
print(longitudeArray)
thanks Victor Apeland - now I changed the structure of the database. I was not able to do it exactly as you suggested!!
I concatenated the lon/lat as a string (not the best - i know - I'm a newbie to swift, and firebase is not well documented)
to retrieve the individual elements from my long/lat, I used this method, and I was particular interested in the first reading, so I made a list, populated it, and got the first element, parsing it to a new method
func responsePosition() {
var positions = [String]()
ref?.child("Vandreture").child(fileName).child("position").observe(.value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! String
positions.append(userDict)
}
let pos : String = positions[0]
self.formatPositions(pos : pos)
})
}
In my firebase lon-lat was divided by a space, so I split the string and cast to double.
func formatPositions(pos : String) {
let lotLangDivided = pos.components(separatedBy: " ")
let longitude = Double(lotLangDivided[0])
let latitude = Double(lotLangDivided[1])
}
now I got the result i wanted
- thanks for the help Victor and Khuong :)
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.