Fetch all user's first names in Firebase - ios

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

Related

How do I get from Firebase database the most recent data in swift?

I am storing data in my firebase database but when I want to retrieve the differents name of my users, unlike my profile image who is retrieving from most recent, the names are retrieving in alphabetical orders... here's my code :
func getNamesUser(){
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "name")
query.observeSingleEvent(of: .value) { (snapshot) in
let nameArray = snapshot.children.allObjects as! [DataSnapshot]
for child in nameArray{
let value = child.value as? NSDictionary
let child = value?["name"] as? String
self.arrayName.append(child!)
}
self.collectionView.reloadData()
}
}
func getImgUser(){
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "profileImgURL")
query.observeSingleEvent(of: .value) { (snapshot) in
let nameArray = snapshot.children.allObjects as! [DataSnapshot]
for child in nameArray{
let value = child.value as? NSDictionary
let child = value?["profileImgURL"] as? String
self.arrayProfilImage.append(child!)
}
self.collectionView.reloadData()
}
}
and here's my firebase database tree :

Firebase retrieve data below auto ID In Swift

I'm in trouble in retrieving data from Firebase.
I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView.
Here is my JSON tree (used childByAutoId())
And Here is my Swift Code
dbRef = Database.database().reference()
dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in
for snap in snapshot.children {
let userSnap = snap as! DataSnapshot
let contactName = userSnap.value as? String
self.pickOption.append("\(contactName)")
}
})
But the result shows me all nil data... looks like this.
How Can I fix it..?
I solved myself!
But first of all, I decided not to use UIPickerView.
And what I wanna do is to add data below auto ID.
I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :)
dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
let orderID = child.key as String //get autoID
self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in
if let nameDB = snapshot.value as? String {
if self.debtorName == nameDB {
self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data)
}
}
})
}
}
})

Swift Get Specific Value From Firebase Database

I'm trying to get a specific value from Firebase Database. I looked some of the documents such as Google's, but I couldn't do it. Here is the JSON file of the database:
{
"Kullanıcı" : {
"ahmetozrahat25" : {
"E-Mail" : "ahmetozrahat25#gmail.com",
"Yetki" : "user"
},
"banuozrht" : {
"E-Mail" : "banuozrahat#gmail.com",
"Yetki" : "user"
}
}
}
Swift Code:
ref?.child("Kullanıcı").child(userName.text!).observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})
I want to get E-Mail value of a user, not everybody's. How can I do that?
At last I found a solution. If I declare a var and try to use later it returns nil, but if I try use snapshot.value as? String it's ok. Here is a example I did.
ref: FIRDatabaseReference?
handle: FIRDatabaseHandle?
let user = FIRAuth.auth()?.currentUser
ref = FIRDatabase.database().reference()
handle = ref?.child("Kullanıcı").child((user?.uid)!).child("Yetki").observe(.value, with: { (snapshot) in
if let value = snapshot.value as? String{
if snapshot.value as? String == "admin"{
self.items.append("Soru Gönder")
self.self.tblView.reloadData()
}
}
})
In your code, the snapshot will contain a dictionary of child values. To access them, cast the snapshot.value as a Dictionary and then accessing the individual children is a snap (shot, lol)
ref?.child("Kullanıcı").child(userName.text!)
.observeSingleEvent(of: .value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
let email = userDict["E-Mail"] as! String
let yetki = userDict["Yetki"] as! String
print("email: \(email) yetki: \(yetki)")
})
Add the "E-Mail" child to the query.
ref?.child("Kullanıcı").child(userName.text!).child("E-Mail").observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.changedName = item
}
})

Firebase Accessing Snapshot Value Error in Swift 3

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

Swift3 Firebase retrieve data

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

Resources