Swift 3 How to get specific user id in firebase - ios

I am using firebase as backend and I want all user id with status false.
What I am trying in my code:-
ref.child("users").child((Auth.auth().currentUser?.uid)!).child("status").queryOrdered(byChild: "status").queryEqual(toValue : "false").observe(.value) { (snapshot: DataSnapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
print("SNAPSHOT: \(snapshot)")
for snap in snapshot {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
print(key)
print(postDict)
}
}
}
}

Find sample code below. Just verify syntax once.
ref.child("users").observe(DataEventType.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
print("SNAPSHOT: \(snapshot)")
for snap in snapshot {
if let userDict = snap.value as? Dictionary<String, AnyObject> {
if userDict["Status"] as? Bool == false {
let key = snap.key
print(key)
//Add this key to userID array
}
}
}
}
}

Related

How to wait until firebase realtime database return data iOS Swift [duplicate]

This question already has answers here:
Returning data from async call in Swift function
(13 answers)
Closed 2 years ago.
I'm a newbie to both Swift and Firebase, I don't Firebase is async connection and I don't know the best practice how to control the the program to wait for the return of data from Firebase and then proceed to next line.
Here is my code: I need to make two queries and once they were completed, then move on the the function prepareSelectedDftList, but the problem is the function is get called before Firebase return. Appreciated to give me some guidance how to fix it. Thank you.
ref = Database.database().reference().child(dftNode)
ref.observe(DataEventType.value, with: { (snapshot) in
// need to consider the workshop is still empty or not?
if snapshot.childrenCount > 0 {
// get defect list
for defect in snapshot.children.allObjects as! [DataSnapshot] {
let defectObj = defect.value as? [String: AnyObject]
let defectId = defect.key
let defectName = defectObj?["name"]
self.tmpDisplayDefectIdList.append(defectId)
self.tmpDisplayDefectNameList.append(defectName as! String)
self.tmpDefectSelected.append(0)
}
}
})
selectedDft = Database.database().reference().child(node)
selectedDft.queryOrderedByKey().queryEqual(toValue: passInCompId).observe(.childAdded, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let tmpkey = snap.key as String?
self.selectedDftId.append(tmpkey!)
}
self.prepareSelectedDftList()
})
You need to do like this:
ref = Database.database().reference().child(dftNode)
ref.observe(DataEventType.value, with: { (snapshot) in
// need to consider the workshop is still empty or not?
if snapshot.childrenCount > 0 {
// get defect list
for defect in snapshot.children.allObjects as! [DataSnapshot] {
let defectObj = defect.value as? [String: AnyObject]
let defectId = defect.key
let defectName = defectObj?["name"]
self.tmpDisplayDefectIdList.append(defectId)
self.tmpDisplayDefectNameList.append(defectName as! String)
self.tmpDefectSelected.append(0)
}
}
selectedDft = Database.database().reference().child(node)
selectedDft.queryOrderedByKey().queryEqual(toValue: passInCompId).observe(.childAdded, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let tmpkey = snap.key as String?
self.selectedDftId.append(tmpkey!)
}
self.prepareSelectedDftList()
})
})
OR Call both in parallelly
var i = 0
ref = Database.database().reference().child(dftNode)
ref.observe(DataEventType.value, with: { (snapshot) in
// need to consider the workshop is still empty or not?
if snapshot.childrenCount > 0 {
// get defect list
for defect in snapshot.children.allObjects as! [DataSnapshot] {
let defectObj = defect.value as? [String: AnyObject]
let defectId = defect.key
let defectName = defectObj?["name"]
self.tmpDisplayDefectIdList.append(defectId)
self.tmpDisplayDefectNameList.append(defectName as! String)
self.tmpDefectSelected.append(0)
}
}
i = i + 1
if i == 2{
self.prepareSelectedDftList()
}
})
selectedDft = Database.database().reference().child(node)
selectedDft.queryOrderedByKey().queryEqual(toValue: passInCompId).observe(.childAdded, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let tmpkey = snap.key as String?
self.selectedDftId.append(tmpkey!)
}
i = i + 1
if i == 2{
self.prepareSelectedDftList()
}
})

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 :

I cannot get the data from my snapshot to load into my tableView cells

ref = Database.database().reference()
ref.child("Clubs").observe(.value, with: { (snapshot : DataSnapshot) in
print("clubs: \(snapshot)")
if let childSnapshot = snapshot.value as? [String : AnyObject] {
print("myClubs: \(childSnapshot)")
From this point, i am unable to get the "name" and "bannerImage" to load into my tableView
if let clubName = childSnapshot["name"] as? String, let banner = childSnapshot["bannerImage"] as? String {
print(clubName)
print(banner)
let club = Club(name: clubName, image: banner)
print("new club success: \(club)")
self.nightClubs.append(club)
self.tableView.reloadData()
}
Use this:-
ref = Database.database().reference()
ref.child("Clubs").observe(.value, with: { (snapshot) in
print("clubs: \(snapshot)")
if(snapshot.exists()) {
let array:NSArray = snapshot.children.allObjects as NSArray
for obj in array {
let snapshot:FIRDataSnapshot = obj as! FIRDataSnapshot
if let childSnapshot = snapshot.value as? [String : AnyObject] {
print("myClubs: \(childSnapshot)")
if let clubName = childSnapshot["name"] as? String, let banner = childSnapshot["bannerImage"] as? String {
print(clubName)
print(banner)
let club = Club(name: clubName, image: banner)
print("new club success: \(club)")
self.nightClubs.append(club)
}
}
}
self.tableView.reloadData()
}
}

Firebase Multi Level Database into tableview

How do I get data from a child deeper into a database that has an unknown name?
My example structure is below.
This code works (to get the snapshot data) but I am hardcoding the second child. I will not always know this value (Bus 1).
let ref = FIRDatabase.database().reference()
let usersRef = ref.child("Trips").child("Bus 1")
usersRef.observeSingleEvent(of: .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:AnyObject] //child data
let personOn = userDict["getOn"] as! String
print("key = \(uid) is at getOn = \(personOn)")
}
})
This will print:
key = Stop 1 is at getOn = 3
key = Stop 2 is at getOn = 7
Should I be structuring this differently? Flatter?
Thanks and let me know of any questions.
This is a more preferable way as I have a class for TripDetails which goes into an array to load into the table. But again, I do not know what the second child's name is.
FIRDatabase.database().reference().child("Trips").child("Bus 1").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let trip = TripDetails()
trip.setValuesForKeys(dictionary)
self.trips.append(trip)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
print(snapshot)
}, withCancel: nil)
I'm still not super sure what data you want exactly. If all you want is all the data you can just do this.
let ref = FIRDatabase.database().reference().child("Trips")
ref.observeSingleEvent(of: .value, with: { snapshot in
let enumerator = snapshot.children
while let bus = enumerator.nextObject() as? FIRDataSnapshot {
print("\(bus.key)")
let enumerator = bus.children
while let stop = enumerator.nextObject() as? FIRDataSnapshot {
let stopDict = stop.value as? [String: Any]
let uid = stop.key
let personOn = stopDict?["getOn"] as? String
print("key = \(uid) is at getOn = \(personOn)")
}
}
})

Firebase: Access a snapshots children using swift3

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

Resources