Im trying to retrieve a specific node in all my children and want to collect all the "role" in every child under "Users"
Here is the database setup:
Users:
25TWFD7SLmQ3onRUdffvfx6Nfmw1:
role: "officer"
9OwM6FIPZgOKu3zzVYSrkPWR0Ij2
role: "advisor"
How can I retrieve all of the "role" nodes?
here you can get the particular node "role".
//To get the all record
let ref = Database.database().reference()
ref.child("Users").childByAutoId().queryOrdered(byChild: "role").observeSingleEvent(of: .value) { (snapshot) in
//To check the data
guard let userDict = snapshot.value as? [String:Any] else {
return
}
let keyArray = [String] (userDict.keys)
for key in keyArray {
if var dataDict = userDict[key] as? [String:Any] {
self.userRoleArray.append(dataDict)
}
}
}
Hopefully this will work for you.
happy coding...
Related
I am trying to list all the users from a firebase node in a table view (this is working) but would then like to remove the current user from the list (this is not working).
I've tried to use removeValue() but it still ran with the current user on the table view - also I don't want to remove the user from firebase
I then tried to make it run only if the the user autoId is not equal to the current users Id but it still shows up on the table view cell
Would appreciate any help :)
My firebase structure is like this:
"users" : {
"8x1SGi2P0KVOKm4i60JQLP1bdU63" : {
"fullname" : "bbbb",
"profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2F8x1SGi2P0KVOKm4i60JQLP1bdU63?alt=media&token=7932b14f-c2d8-46fd-9dd1-c607217fe8d3",
},
"B7rwHiCTlphZjKXfPSEzkIwl8RH2" : {
"fullname" : "Aaaa ",
"profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2FB7rwHiCTlphZjKXfPSEzkIwl8RH2?alt=media&token=072e1f41-935e-430d-af99-dc640381f8e6",
},
"FRuuk20CHrhNlYIBmgN4TTz3Cxn1" : {
"fullname" : "eeee",
"profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2FFRuuk20CHrhNlYIBmgN4TTz3Cxn1?alt=media&token=bf89b903-a51a-4d6d-bdef-fe2667d78842",
},
Code to which lists users:
func observeUsers(completion: #escaping (UserModel) -> Void) {
REF_USERS.observeSingleEvent(of: .childAdded, with: { snapshot in
if let dict = snapshot.value as? [String: Any] {
let user = UserModel.transformUser(dict: dict, key: snapshot.key)
//line below used first to remove value from listing on table view
//Api.User.REF_USERS.child("users").child(Api.User.CURRENT_USER!.uid).removeValue()
//line below - if user autoID is not equal to the current user then list
if user.id != Api.User.CURRENT_USER?.uid {
completion(user)
}
}
})
}
EDIT:
func loadUsers() {
var allUsers = [String]()
Api.User.REF_USERS.observe(.value, with: { snapshot in
for child in snapshot.children { //build the array of keys
let snap = child as! DataSnapshot
let key = snap.key
allUsers.append(key)
print(allUsers)
}
})
}
instead of removing try this
create model of your tabledata
then create an empty array of it
while fetching the data append all except that which has same currentuser.uid
then reload the tableview this will show all the data except the current user
this is the code as promised:
but this need a little modification in your database
make your database like this
"users":{
"childbyautid":{
"fullname": "name",
"profileimageurl": "your url",
"userid": "userid"
}
then you can write like this
var myArr = [String]()
Database.database().reference.child("users").observe(.value){(snapshot) in
if snapshot.childcount > 1 { self.myArr.removeAll()
for data in snapshot.children.allObjects as! [DataSnapshot]{
if let d = data.value as? [string: any]{
if Auth.auth.currentuser.uid != d["userid"]{
myArr.append(d["name"]}else{print("this is the user itself"}}}
You can control this in you loadUsers by adding userId check like below
func loadUsers() {
var allUsers = [String]()
Api.User.REF_USERS.observe(.value, with: { snapshot in
for child in snapshot.children { //build the array of keys
let snap = child as! DataSnapshot
let key = snap.key
if key != currentUser.id{
allUsers.append(key)
}
print(allUsers)
}
})
}
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 created JSON database tree and I can read specific values with these codes. I can see on table view "Albert Einstein"
ref.child("Personel").child("Name").observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.myList.append(item)
self.LessonsTableView.reloadData()
}
})
But, I want to see which categories under Personal column? Like this,
Is there any way to get or learn which columns are under "Personal"
Table view output must be -> Age, Name, Photo
You can iterate over the snapshot, get it's children and then those childrens keys
Say you have a users node with a user
users
user_0
fav_game: "WoW"
name: "Leroy"
then to get the keys of name: and fav_game:
let userRef = self.ref.child("users").child("user_0")
userRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
print(key)
}
})
prints
fav_game
name
An important note is
for child in snapshot.children
because that will keep the data (keys in this case) in order. If the snapshot is dumped into a dictionary it looses order.
If you loop through snapshot.value you should be able to get the keys from the database.
In JavaScript it would be something like:
ref.child("Personel").child("Name").observeSingleEvent(of: .value, with: { (snapshot) in
if let item = snapshot.value as? String{
self.myList.append(item)
self.LessonsTableView.reloadData()
}
var vals = snapshot.val();
for(var property in vals) {
console.log(property); // property has those values in it
}
})
This is one way:
ref.child("Personel").observeSingleEvent(of: .value, with: { (snapshot) in
self.myList.append(snapshot.childSnapshot(forPath: "Age").value)
self.myList.append(snapshot.childSnapshot(forPath: "Name").value)
self.myList.append(snapshot.childSnapshot(forPath: "Photo").value)
self.LessonsTableView.reloadData()
})
I need to make multiple observations, but I don't know how.
Here is my database structure:
"Posts" : {
"f934f8j3f8" : {
"data" : "",
"date" : "",
"userid" : ""
}
},
"Users" : {
"BusWttqaf9bWP224EQ6lOEJezLO2" : {
"Country" : "",
"DOB" : "",
"Posts" : {
"f934f8j3f8" : true
},
"Profilepic" : "",
"name" : "",
"phonenumber" : ""
}
I want to observe the posts and I write the code and it works great, but I also want to get the name of the user who posted this post but when I wrote save the name and use it it gives me null. Here is my code.
DataServices.ds.REF_POSTS.queryOrderedByKey().observe(.value,
with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
if let postsDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let userID = "BusWttqaf9bWP224EQ6lOEJezLO2"
DataServices.ds.REF_USERS.child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let postusername = value?["name"] as? String ?? ""
})
print(" ------ User name : \(postusername) ------")
})
print(" ------ User name 2 : \(postusername) ------")
let post = Posts(postKey: key, postData: postsDict)
self.posts.append(post)
The first print statement prints the username, but the second one prints nothing.
Thanks in advance.
Firebase is asynchronous so you can't operate on a variable until Firebase populates it within it's closure. Additionally code is faster than the internet so any statements following a closure will occur before the statements within the closure.
The flow would be as follows
Query for the post {
get the user id from the post inside this closure
query for the user info {
create the post inside this second closure
append the data to the array inside this second closure
reload tableview etc inside this second closure
}
}
Something like this edited code
self.posts = []
myPostsRef.queryOrderedByKey().observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
if let postsDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let userID = "BusWttqaf9bWP224EQ6lOEJezLO2"
myUsersRef.child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let userName = value?["name"] as? String ?? ""
let post = Posts(postKey: key, postData: postsDict, name:userName)
self.posts.append(post)
})
}
}
}
})
You're not using the postusername inside the closure so I added that to the Posts initialization.
Also, the self.posts = [] is going to reset the posts array any time there's a change in the posts node - you may want to consider loading the array first, and then watch for adds, changes, or deletes and just update the posts array with single changes instead of reloading the entire array each time.
Edit:
A comment was made about the data not being available outside the loop. Here is a very simplified and tested version. Clicking button one populates the array from Firebase with a series of strings, clicking button 2 prints the array.
var posts = [String]()
func doButton1Action() {
let postsRef = ref.child("posts")
self.posts = []
postsRef.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
let value = snap.value as! String
self.posts.append(value)
}
}
})
}
func doButton2Action() {
print(posts)
}
I have a "flatened" Firebase structure and trying to retrieve a dictionary of values from a "secondary" database member. In other words, I have a conversation which has a "to" cell which has the key to a business listing. With this key, I'm trying to retrieve the business listing and its children (url, description, title). For some reason, I can print the snapshot2.value and it responds with the expected value, but I can't pass it to my class initialization.
DataService.ds.REF_CONVOS.observeEventType(.Value, withBlock: {snapshot in
self.convoListings.removeAll()
self.convoListings = []
//Data parsing from Firebase. The goal is to breakdown the data received and store in a local model.
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
for convo in userConvos {
// Going into the children of the main object for the conversations.
//print("\(snap)")
if convo == snap.key {
//print(snap.value)
print(snap.value)
if let businessDict = snap.value as? Dictionary<String, AnyObject> {
businessName.removeAll()
let test = businessDict["to"] as? String
DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
print(snapshot2.value)
})
let key = snap.key
let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
self.convoListings.append(post)
}
}
}
}
}
self.tableView.reloadData()
})
Your nesting seems of:
DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
print(snapshot2.value)
})
let key = snap.key
let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
self.convoListings.append(post)
Keep in mind the observeSingleEventOfType loads the data asynchronously. For this reason, if you have code that needs the value that you loaded, you need to put that code in the block:
DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
print(snapshot2.value)
let key = snap.key
let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
self.convoListings.append(post)
})