I'm working on a follow friends view controller that loads all the usernames in the database, BUT I don't want it to load the current user's username. I need to access the username from the currentUser's uid, and add all the usernames that are not equal to it to my array.
#objc func loadData() {
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "username")
query.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.value as? NSDictionary
let username = value?["username"] as? String ?? ""
if username != rootRef.child(Auth.auth().currentUser!.uid).value(forKey: "username") as! String{
self.usernames.append(username)
}
print(username)
}
self.tableView.reloadData()
print(self.usernames)
}
}
You should try and minimise queries inside loops, especially irrelevent ones. Given your database schema uses the users unique id as the key, you can run your evaluation based on that key using child.key.
#objc func loadData() {
let rootRef = Database.database().reference()
let query = rootRef.child("users").queryOrdered(byChild: "username")
query.observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = child.value as? NSDictionary
let username = value?["username"] as? String ?? ""
if Auth.auth().currentUser!.uid != child.key {
self.usernames.append(username)
}
print(username)
}
self.tableView.reloadData()
print(self.usernames)
}
}
Related
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'm Trying to check if the rooms's value 'Owner' equals to the current user id if so then fetch all data including the key value and continue checking other children of 'rooms'
I was trying, but I fail finding the solution though it might seem easy so please help me with your suggestions or ideas. My code so far :
Database.database().reference().child("rooms").queryOrdered(byChild: "Owner").observeSingleEvent(of: .value, with: { (snapshot) in
let currentUser = Auth.auth().currentUser?.uid
if !snapshot.exists() {
print("No data found")
return
}
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: roomKey,title: title!, description: description!, roomPicutreURL: roomPictureUrl!, longitude: longitude!, latitude: latitude!, dateFrom: dateFrom!, dateTo: dateTo!, owner: owner!)
self.rooms.append(myRooms)
self.tableView.reloadData()
print(snapshot.value)
}
})
You're missing the value in your query:
Database.database().reference()
.child("rooms")
.queryOrdered(byChild: "Owner")
.queryEqual(toValue: "STbz...")
.observeSingleEvent(of: .value, with: { (snapshot) in
See for this and more query operators, the documentation on filtering data.
Mark:- Swift 5
Database.database().reference().child("user")
.queryOrdered(byChild: "UserPhoneNumber") //in which column you want to find
.queryEqual(toValue: "Your phone number or any column value")
.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.childrenCount > 0
{
if let snapShot = snapshot.children.allObjects as? [DataSnapshot] {
//MARK:- User Exist in database
for snap in snapShot{
//MARK:- User auto id for exist user
print(snap.key)
break
}
}
}
else if snapshot.childrenCount == 0
{
//MARK:- User not exist no data found
}
})
I tried to set up a function to listen for changes within a certain part of my database:
private func observeParticipants() {
let databaseRef = FIRDatabase.database().reference()
let groupRef = databaseRef.child("groups").child(currentRoomID).child("participants")
groupRef.observe(.childAdded, with: { snapshot in
print("observe snapshot.value: \(snapshot.value)")
if let snapDict = snapshot.value as? [String:AnyObject] {
for each in snapDict {
let uid = each.key
let avatar = each.value["profilePicture"] as! String
let gender = each.value["gender"] as! String
let handle = each.value["handle"] as! String
let name = each.value["name"] as! String
let status = each.value["status"] as! String
// Set those to the dictionaries [UID : value]
self.avatarDictionary.setValue(avatar, forKey: uid)
self.nameDictionary.setValue(name, forKey: uid)
self.genderDictionary.setValue(gender, forKey: uid)
self.handleDictionary.setValue(handle, forKey: uid)
self.statusDictionary.setValue(status, forKey: uid)
print("\n\navatarDictionary:\n \(self.avatarDictionary)")
print("\nhandleDictionary:\n \(self.handleDictionary)")
print("\ngenderDictionary:\n \(self.genderDictionary)")
print("\nnameDictionary:\n \(self.nameDictionary)")
print("\nstatusDictionary:\n \(self.statusDictionary)")
self.navBarCollectionView.reloadData()
}
}
})
}
When I run this, it loads the correct values, but if I make a change, for example add a new user to the group, it doesn't reflect that change. The database is updated fine, but the observer isn't seeing that. Is there any way I can re-write this to make is observe properly? I can post my database structure if it will help.
Thanks!
EDIT: Database structure:
https://pastebin.com/SZ2mE2Vt
EDIT: snapshot.value after adding second user:
Snapshot.value: Optional({
gender = female;
handle = sav;
name = Savina;
profilePicture = "https://graph.facebook.com/1929991317219760/picture?type=large&return_ssl_resources=1";
status = F8B016;
})
EDIT 2:
This is the code that works for fetching all user values initially, and also every time I leave the view and come back. It just doesn't act properly as an observer, i.e. if I add a participant, it doesn't see that and update the necessary values such as the collection view. I have to leave the view and come back for that to happen.
func getParticipantInfo() {
let databaseRef = FIRDatabase.database().reference()
let groupRef = databaseRef.child("groups").child(currentRoomIdGlobal)
groupRef.observe(.childAdded, with: { snapshot in
if let snapDict = snapshot.value as? [String : AnyObject] {
for each in snapDict {
let uid = each.key
let avatar = each.value["profilePicture"] as! String
let gender = each.value["gender"] as! String
let handle = each.value["handle"] as! String
let name = each.value["name"] as! String
let status = each.value["status"] as! String
// Set those to the dictionaries [UID : value]
self.avatarDictionary.setValue(avatar, forKey: uid)
self.nameDictionary.setValue(name, forKey: uid)
self.genderDictionary.setValue(gender, forKey: uid)
self.handleDictionary.setValue(handle, forKey: uid)
self.statusDictionary.setValue(status, forKey: uid)
print("\n\navatarDictionary:\n \(self.avatarDictionary)")
print("\nhandleDictionary:\n \(self.handleDictionary)")
print("\ngenderDictionary:\n \(self.genderDictionary)")
print("\nnameDictionary:\n \(self.nameDictionary)")
print("\nstatusDictionary:\n \(self.statusDictionary)")
self.navBarCollectionView.reloadData()
}
}
})
}
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 am trying to fetch all the driveways which belongs to user using their email as the search key.
And here is the code I am writing:
guard let currentUser = FIRAuth.auth()?.currentUser else {
return
}
let query = FIRDatabase.database().reference(withPath :"driveways").queryEqual(toValue: currentUser.email!, childKey: "email")
query.observe(.value, with: { (snapshot) in
print(snapshot)
})
How can I get all the driveways based on user's email address?
Try this (Swift 3 Firebase 3)
let email = "johndoe#gmail.com"
let queryRef = drivewaysRef.queryOrdered(byChild: "email")
.queryEqual(toValue: email)
queryRef.observeSingleEvent(of: .value, with: { snapshot in
for snap in snapshot.children {
let driveSnap = snap as! FIRDataSnapshot
let driveDict = driveSnap.value as! [String:AnyObject] //driveway child data
let city = driveDict["city"] as! String
let state = driveDict["state"] as! String
print("email: \(email) city: \(city) state: \(state)")
}
})