I am struggling with getting some of the data from my Firebase. This is how the structure looks like:
This is the code I retrieve the data with:
var followDatesDict = [String:String]()
databaseRef.child("FollowGroups").child(selectedFollowGroupId as String).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChildren(){
let name = snapshot.childSnapshot(forPath: "followgroupTitle").value as! String
let sDate = snapshot.childSnapshot(forPath: "startDate").value as! String
let eDate = snapshot.childSnapshot(forPath: "endDate").value as! String
followDatesDict = snapshot.childSnapshot(forPath: "followDates")......
}
})
I can retrieve name, sDate, and eDate just fine. But does anyone know how I can fill up the followDatesDict ordered by date? As you see in the structure of followDates, the key is a String of dates and a String value.
Thanks!
Ok, I managed to get the data. I also add them into a struct.
let enumerator = snapshot.childSnapshot(forPath: "followDates").children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
let key_followDate = rest.key
let value_UserId = rest.value as! String
//add to dictionary
self.followDatesDict.insert(followgroupOverview(followDate:key_followDate, followUserId:value_UserId), at: 0)
}
Related
I'm getting the error of could not cast value of type 'FIRDataSnapshot' to 'NSString'. Neither the retrieve names or retrieve quantities/manfacturers is working. Both give the same casting error essentially.
ref = Database.database().reference()
// Retrieve Names
ref.child("rawMaterials").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
self.rawMaterialNames.append(child as! String)
}
})
//Retrieve Quantities and Manfacturers
for name in rawMaterialNames {
ref.child("rawMaterials/\(name)").observe(.value, with: { (snapshot) in
if let data = snapshot.value as? [String: Any] {
for i in data {
let quantity = data["quantity"] as! String
let manafacturer = data["manafacturer"] as! String
self.rawMaterialManafacturers.append(manafacturer)
self.rawMaterialQuantities.append(quantity)
//self.rawMaterialQuantities.append(data!["quantity"] as! String)
//self.rawMaterialManafacturers.append(data!["manafacturer"] as! String)
}
}
})
Edit: Since, no one has been able to help, maybe I'm not providing enough. My firebase realtime database tree looks like this
App Name
-contracts
---ContractTest
-rawMaterials
---Optional("Paint")
--------manafacturer: "Optional(\"Paint Company A\")"
--------quantity: "Optional(\"120\")"
---Optional("Lead")
You are missing a step to be able to cast to String:
ref.child("rawMaterials").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let nameSnapshotValue = child.value as! FIRDataSnapshot
let name = nameSnapshotValue["name"] as! String //or whatever the dictionary key is...
self.rawMaterialNames.append(name)
}
})
I'm trying to retrieve all user's firstnames in my Firebase database. What is the best way to add them to an array?
Firebase database
-Users
-UserId1
- firstname: James
-UserId2
- firstname: Jennifer
Swift code
let rootRef = Database.database().reference()
let query = rootRef.child("Users").queryOrdered(byChild: "firstname")
query.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = snapshot.value as? NSDictionary
let firstname = value?["firstname"] as? String ?? ""
print(firstname)
}
}
Might just be a typo ;) You should be using child inside your loop instead of snapshot. For instance, try replacing the following line:
let value = snapshot.value as? NSDictionary
with:
let value = child.value as? NSDictionary
Please anyone who would show me how to include the snapshot key value along with children value that I already append to my array (forgot to include it and now remember I have to) ... aside from that something really I couldn't understand when I tried to solve my own issue, by testing the value first by using this method: print(rooms.popFirst().key!) half of my database values got nil value ?!! and if I don't include that method everything works fine anyways if you can't imagine that nonetheless I really wish your suggestion or advice for getting all data with their own key value...
This is my code so far:
Database.database().reference().child("rooms").observe(.value, with: { (snapshot) in
print()
var rooms = snapshot.value as! [String:AnyObject]
for(_,value) in rooms {
if (rooms.popFirst()?.key) != nil{
let title = value["title"] as? String
let description = value["description"] as? String
let roomPictureUrl = value["Room Picture"] as? String
let longitude = value["Longtitude"] as? String
let latitude = value["Latitude"] as? String
let dateFrom = value["Date From"] as? String
let dateTo = value["Date To"] as? String
let owner = value["Owner"] as? String
let myRooms = Room(roomID: "XXX",title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!)
//print(rooms.popFirst()?.key)
self.rooms.append(myRooms)
self.tableView.reloadData()
}
}
})
Try this:
Database.database().reference().child("rooms").observe(.value, with: { (snapshot) in
var rooms = snapshot.value as! [String:AnyObject]
let roomKeys = Array(rooms.keys)
for roomKey in roomKeys {
guard
let value = rooms[roomKey] as? [String:AnyObject]
else
{
continue
}
let title = value["title"] as? String
let description = value["description"] as? String
let roomPictureUrl = value["Room Picture"] as? String
let longitude = value["Longtitude"] as? String
let latitude = value["Latitude"] as? String
let dateFrom = value["Date From"] as? String
let dateTo = value["Date To"] as? String
let owner = value["Owner"] as? String
let myRooms = Room(roomID: "XXX",title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!)
print(roomKey)
self.rooms.append(myRooms)
self.tableView.reloadData()
}
}
})
To get the key from snapshot you can use following lines of code it will give you result like -> Kqwewsds12 -> your child Details
let dictValues = [String](snapshot.keys)
print(dictValues[0]) //Output -- Kqwewsds12
I'm trying to get the value of multiple children of my snapshot in order to append my cellDataArray by name and speed.
My code is working for name, but not for speed..
ref = FIRDatabase.database().reference().child("BasicInfo")
let query = ref?.queryOrdered(byChild: "Operator")
query?.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let name = child.key
let speed = child.childSnapshot(forPath: "Speed")
self.cellDataArray.append(cellData(mainText: name, Speed: ""))
self.tableView.reloadData()
}
})
This is my Firebase structure:
Try to access the value property of FIRDataSnapshot to get the Speed.
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let name = child.key
if let dic = child.value as? [String:Any], let speed = dic["Speed"] as? Int
let operator = dic["Operator"] as? String {
print(operator)
self.cellDataArray.append(cellData(mainText: name, Speed: "\(speed)"))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.
My code:
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value!["fullName"] as! String
let homeAddress = snapshot.value!["homeAddress"] as! [Double]
let email = snapshot.value!["email"] as! String
}
The error is around the three variables stated above and states:
Type 'Any' has no subscript members
Any help would be much appreciated
I think that you probably need to cast your snapshot.value as a NSDictionary.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["fullName"] as? String ?? ""
let homeAddress = value?["homeAddress"] as? [Double] ?? []
let email = value?["email"] as? String ?? ""
}
You can take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write
When Firebase returns data, snapshot.value is of type Any? so as you as the developer can choose to cast it to whatever data type you desire. This means that snapshot.value can be anything from a simple Int to even function types.
Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
{
let username = firebaseDic["fullName"] as! String
let homeAddress = firebaseDic["homeAddress"] as! [Double]
let email = firebaseDic["email"] as! String
}
else
{
print("Error retrieving FrB data") // snapshot value is nil
}
}