Error downloading posts from Firebase's Database (Swift 3) - ios

I have a social app that have posts like Facebook but when i try to download the posts it returns nil.
FIRDatabase.database().reference().child("following").child(FIRAuth.auth()!.currentUser!.uid).queryOrderedByValue().queryEqual(toValue: true).observeSingleEvent(of: .value, with: {(snap) in
if let snapDict = snap.value as? [String:AnyObject]{
for each in snapDict{
FIRDatabase.database().reference().child("Posts").child(String(each.key)).queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: {(snapshot) in
if (snapshot.value != nil)
{
self.Posts.append(snapshot.value as! NSDictionary)
}
}){(error) in
print(error.localizedDescription)
}
}
}
self.homeTableView.reloadData()
self.aivLoading.stopAnimating()
})
after some debugging i reduce the problem to this line of code that return then nil value
FIRDatabase.database().reference().child("Posts").child(String(each.key)).queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: {(snapshot) in
the other part of my code does return the list of people you follow and loops thought it.
this is the structure of my database.
{
"Posts" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"-KbHUnL-RveUQa3MPSWp" : {
"latitud" : "21.111401000574",
"longitud" : "-89.6112191677094",
"text" : "Fiesta en la Anahuac!!! ",
"timestamp" : "1485295269.30773",
"ubicacionN" : "Universidad Anáhuac Mayab"
},
"-KbI1azr6uFel-5uTZOD" : {
"latitud" : "Optional(21.018988764483463)",
"longitud" : "Optional(-89.614319546492695)",
"text" : "Hola chicos",
"timestamp" : "1485304393.77929",
"ubicacionN" : "Calle 53-A 341"
},
"-KbNQWxjQhc0Ce_ZQbq9" : {
"latitud" : "Optional(21.019219877217914)",
"longitud" : "Optional(-89.614173537203683)",
"text" : "Hola",
"timestamp" : "1485394812.83039",
"ubicacionN" : "Calle 53 341"
}
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"-KbQOWfUnzY1JiS61J6-" : {
"latitud" : "Optional(21.111502615883129)",
"longitud" : "Optional(-89.611767497121221)",
"text" : "Hola chicos!",
"timestamp" : "1485444619.10931",
"ubicacionN" : "Carretera Mérida-Progreso 96"
}
}
},
"follower" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"mt0fzirhMhazIcy90MRWuRpTfmE2" : true
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : true
}
},
"following" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"mt0fzirhMhazIcy90MRWuRpTfmE2" : true
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : true
}
},
"handles" : {
"jcadmin" : "mt0fzirhMhazIcy90MRWuRpTfmE2",
"jcbest" : "dEXaVLDOSPfJa3zTyUNqAEtVuMR2"
},
"user_profiles" : {
"dEXaVLDOSPfJa3zTyUNqAEtVuMR2" : {
"about" : "Hola Mundo",
"handle" : "jcbest",
"name" : "Juan Carlos Estevez Rodriguez",
"profile_pic" : "https://firebasestorage.googleapis.com/v0/b/jalo-267da.appspot.com/o/user_profiles%2FOptional(%22dEXaVLDOSPfJa3zTyUNqAEtVuMR2%22)%2Fprofile_pic?alt=media&token=bfc3c516-7849-472c-b7cd-9668965a5dbe"
},
"mt0fzirhMhazIcy90MRWuRpTfmE2" : {
"about" : "Hola chicos",
"handle" : "jcadmin",
"name" : "Juan Carlos",
"profile_pic" : "https://firebasestorage.googleapis.com/v0/b/jalo-267da.appspot.com/o/user_profiles%2FOptional(%22mt0fzirhMhazIcy90MRWuRpTfmE2%22)%2Fprofile_pic?alt=media&token=b741b6c1-0bc5-446d-a1e5-159b21e770d2"
}
}
}
this is my entire code.
https://www.dropbox.com/sh/u7saz4mdbehw1gd/AACv2rZH7M8jS_lU-plSqwc5a?dl=0

If this is a valid data set, then you're looking for the wrong thing in your query, but it could be that I just don't understand your data!
I'm assuming that the currentUser is dEXaVLDOSPfJa3zTyUNqAEtVuMR2, and that the first query to get those following should return mt0fzirhMhazIcy90MRWuRpTfmE2
You don't have any reference to mt0fzirhMhazIcy90MRWuRpTfmE2 in the posts, so you're never going to get anything returned in the second query ...

I found the problem after a lot of debuging and as it tourns out the problem was that in this part
FIRDatabase.database().reference().child("Posts").child(String(each.key)).queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: {(snapshot) in
if (snapshot.value != nil)
{
self.Posts.append(snapshot.value as! NSDictionary)
}
}){(error) in
print(error.localizedDescription)
}
the Query was actually downloading all the posts but they were kept in a non static varaible (noob error) so the only thing I had to do was reload the data just after it got every post, that is to say that it needed to be like this:
FIRDatabase.database().reference().child("Jalas").child(each.key).queryOrderedByKey().observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
print(snapshot.value as! NSDictionary)
self.Jalas.append(snapshot.value as! NSDictionary)
self.homeTableView.reloadData()
})
so the complete code looks something like this:
self.homeTableView.delegate = self
self.homeTableView.dataSource = self
self.loggedInUser = FIRAuth.auth()?.currentUser
print("LoggedInUser: " + (self.loggedInUser?.uid)!)
FIRDatabase.database().reference().child("following").child(FIRAuth.auth()!.currentUser!.uid).queryOrderedByValue().queryEqual(toValue: true).observeSingleEvent(of: .value, with: {(snap) in
//if let snapDict = snap.value as? [String:AnyObject]{
let sanpDict = snap.value as? [String:AnyObject]
if (sanpDict != nil)
{
for each in sanpDict!{
print("each.key es: " + String(each.key))
FIRDatabase.database().reference().child("Jalas").child(each.key).queryOrderedByKey().observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
print(snapshot.value as! NSDictionary)
self.Jalas.append(snapshot.value as! NSDictionary)
self.homeTableView.reloadData()
})
}
}
self.aivLoading.stopAnimating()
})

Related

Get values in Firebase Realtime Database with specific value in Swift [duplicate]

I am trying to get all the entries where createdAt is equal to Today, but it returns nothing.
What am I doing wrong here? And, what is the proper way to query data the way I am trying to do?
JSON:
{
"thoughts" : {
"-KWGdcdZD8QJSLx6rSy8" : {
"createdAt" : "Tomorrow",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
},
"-KWGeGivZl0dH7Ca4kN3" : {
"createdAt" : "Today",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
},
"-KWGeIvWHBga0VQazmEH" : {
"createdAt" : "Yesterday",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
}
}
}
Swift:
let db = FIRDatabase.database().reference().child("thoughts")
let ref = db.queryEqual(toValue: "Today", childKey: "createdAt")
ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in
for snap in snapshot.children {
print((snap as! FIRDataSnapshot).key)
}
})
You need to use queryOrderedByChild to createdAt and than use equalTo Today
let ref = FIRDatabase.database().reference().child("thoughts").queryOrdered(byChild: "createdAt").queryEqual(toValue : "Today")
ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in
for snap in snapshot.children {
print((snap as! FIRDataSnapshot).key)
}
})
This is my solution for this JSON:
JSON:
{
"users" : {
"-KWGdcdZD8QJSLx6rSy8" : {
"name" : "dummy1",
"visibility" : true
},
"-KWGeGivZl0dH7Ca4kN3" : {
"name" : "dummy2",
"visibility" : false
},
"-KWGeIvWHBga0VQazmEH" : {
"name" : "dummy3",
"visibility" : true
}
}
}
SWIFT:
//Fetch only Childs with attribute "visibility" = true
Database.database().reference().child("users").queryOrdered(byChild: "visibility").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:Any] else {return}
dictionary.forEach({ (key , value) in
print("Key \(key), value \(value) ")
})
}) { (Error) in
print("Failed to fetch: ", Error)
}
My Solution in Swift 5, Hope this will help.
let ref = Database.database().reference().child("thought")
let refHandle=ref.queryOrdered(byChild:"thoughts").queryEqual(toValue:"Today").observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
let snap = snapshot.value as? [String:Any]
print(snap)
}
})

Firebase .queryStarting not working (Swift)

This just isn't returning anything even though there are messages with timestamps above this one.
Code not properly sorting:
let messagesRef = FIRDatabase.database().reference().child("all-messages").child(messageId).queryOrdered(byChild: "timestamp").queryStarting(atValue: 1511130644)
Full code of Firebase calls:
FIRDatabase.database().reference().child("users").child(currentUserUid).child("timestampOfLastVisit").observeSingleEvent(of: .value, with: { (snapshot) in
timestamp = snapshot.value as! NSNumber
groupMessagesRef = FIRDatabase.database().reference().child("groups").child(groupId).child("messages")
groupMessagesRef.observe(.childAdded, with: { (snapshot) in
if self.sentMessage {
let messageId = snapshot.key
let messagesRef = FIRDatabase.database().reference().child("all-messages").child(messageId).queryOrdered(byChild: "timestamp").queryStarting(atValue: 1511130644)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in ...
Relevant Firebase JSON (fake data obviously):
{
"all-messages" : {
"-KzLOuvEdLWy7vfc2XsT" : {
"fromId" : "zhBZyAVGvAMZWi4QhvKDu7qb3Qr1",
"groupId" : "-Kxk3kA9I8OEvNmFcavL",
"isStarred" : true,
"text" : "This should show",
"timestamp" : 1511130640
},
"-KzLOw5OxZ4P_I0d70gZ" : {
"fromId" : "zhBZyAVGvAMZWi4QhvKDu7qb3Qr1",
"groupId" : "-Kxk3kA9I8OEvNmFcavL",
"isStarred" : false,
"text" : "And so should this",
"timestamp" : 1511130644
},
"-KzLS4uwDtpW6wHNxrmc" : {
"fromId" : "zhBZyAVGvAMZWi4QhvKDu7qb3Qr1",
"groupId" : "-Kxk3kA9I8OEvNmFcavL",
"isStarred" : false,
"text" : "1",
"timestamp" : 1511131471
},
"-KzLS5FvASnj_ky4WQkd" : {
"fromId" : "zhBZyAVGvAMZWi4QhvKDu7qb3Qr1",
"groupId" : "-Kxk3kA9I8OEvNmFcavL",
"isStarred" : false,
"text" : "2",
"timestamp" : 1511131472
}
},
"groups" : {
"-Kxk3kA9I8OEvNmFcavL" : {
"groupCreator" : "zhBZyAVGvAMZWi4QhvKDu7qb3Qr1",
"groupDescription" : "Group",
"groupImageUrl" : "https://firebasestorage.googleapis.com/v0/b/groupchat1-a1da3.appspot.com/o/group_profile_images%2FA4DDA286-E7A3-4F96-ABF0-5717F4029C33.png?alt=media&token=6ad79728-74fd-405f-abbf-247dae4684b5",
"groupMemberOneSignalIds" : {
"5905a2f5-dfa3-46d7-964f-596bd2f2004a" : true,
"67b9cb2a-6583-45b4-9fed-93cf333e9ca4" : true,
"a1bf9ed9-0959-4c88-974b-5a829c1cdcc9" : true,
"f2fb84b9-86af-40e7-8667-989a95b2e282" : true
},
"groupMembers" : {
"3lQiuzudFGW51UwQ4Mseu8aOxyu2" : true,
"JF7SCe3VUcWJi1ujumx0VpyaG5s1" : true,
"YEbVehx0cqTvNaKrJTcs5GnRLGM2" : true,
"zhBZyAVGvAMZWi4QhvKDu7qb3Qr1" : true
},
"groupName" : "1",
"groupTags" : {
"-Kxk3kHxMuWQHEsaWN5k" : "1",
"-Kxk3kHyMB2OL5pNAfW1" : "1",
"-Kxk3kHyMB2OL5pNAfW2" : "1"
},
"messages" : {
"-KzLOuvEdLWy7vfc2XsT" : 1,
"-KzLOw5OxZ4P_I0d70gZ" : 1,
"-KzLS4uwDtpW6wHNxrmc" : 1,
"-KzLS5FvASnj_ky4WQkd" : 1
},
"starredMessages" : {
"-KzLOuvEdLWy7vfc2XsT" : 1511204335
}
},
"-Kxn_yTAZvkPls-_s8He" : {
"groupCreator" : "JF7SCe3VUcWJi1ujumx0VpyaG5s1",
"groupDescription" : "Group 3",
"groupImageUrl" : "https://firebasestorage.googleapis.com/v0/b/groupchat1-a1da3.appspot.com/o/group_profile_images%2FD2C68A8F-33DC-43C6-8C99-762315760208.png?alt=media&token=aae87339-877e-484e-a0e1-a2e13455176c",
"groupName" : "Group 3",
"groupTags" : {
"-Kxn_ygovR7mQIph3WiC" : "1",
"-Kxn_ygovR7mQIph3WiD" : "1"
}
}
},
"users" : {
"JF7SCe3VUcWJi1ujumx0VpyaG5s1" : {
"email" : "Madi#gmail.com",
"groups" : {
"-Kxk3kA9I8OEvNmFcavL" : true,
"-Kxk3n99i43MYECm1Ix8" : true,
"-KxuBPAPBIcROMEtNujW" : true,
"-KxuET1pZGg2x_aJvRkU" : true
},
"profileImageURL" : "https://firebasestorage.googleapis.com/v0/b/groupchat1-a1da3.appspot.com/o/profile_images%2F246CA55C-446D-4A24-8BE6-8B5B9C0F27AF.png?alt=media&token=47022ccd-1c92-460a-8630-e74a0d68bc4a",
"searchUsername" : "madi",
"timestampOfLastVisit" : 1511241228,
"username" : "Madi"
},
"zhBZyAVGvAMZWi4QhvKDu7qb3Qr1" : {
"email" : "Connor#gmail.com",
"groups" : {
"-Kxk3kA9I8OEvNmFcavL" : true,
"-Kxk3n99i43MYECm1Ix8" : true
},
"profileImageURL" : "https://firebasestorage.googleapis.com/v0/b/groupchat1-a1da3.appspot.com/o/profile_images%2FBDC4020E-9F54-4F80-A4DC-668804215DE3.png?alt=media&token=ec2c8875-e6e4-40d5-8c07-3d743bf4ea16",
"searchUsername" : "connor",
"timestampOfLastVisit" : 1511205356,
"username" : "Connor"
}
}
}
What print(snapshot) prints:
Snap (-KzLOw5OxZ4P_I0d70gZ) <null>
print(messageRef):
(/all-messages/-KzLOw5OxZ4P_I0d70gZ {
i = timestamp;
sp = 1511130644;
})
The goal is to create a query that will return the node that has a particular time stamp.
The problem is your code is querying one level too deep. In other words, you need to let Firebase iterate over the child nodes of all-messages until it finds one that has a child timestamp of 1511130644. So it will need to iterate over
msg_0
msg_1
msg_2
etc.
Your code is trying to be too specific and you are telling it to look at a particular message Id for the data in the query - which doesn't make sense as if you know the exact path, you wouldn't need to query!
This is a common misunderstanding - just remember that queries need to be provided the parent node and then the child node of what you are querying for as it will then iterate over the child_nodes just underneath the parent.
parent_node
child_node
child_node_of_what_you_are_querying
child_node
child_node_of_what_you_are_querying
Here is code to query for a certain time stamp - note the messageId is not needed
//self.ref is the firebase ref
let messagesRef = self.ref.child("all-messages").queryOrdered(byChild: "timestamp")
.queryStarting(atValue: 1511130644)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChildren() {
print("got snap with children")
} else {
print("no snap found")
}
})
If you already know the specific path you can observe it directly. So if you want to print the timestamp for a certain message
let thisMsgRef = self.ref.child("all-messages").child(messageId)
let thisTimestampRef = thisMsgRef.child("timestamp")
thisTimestampRef.observeSingleEvent(of: .value) { snapshot in
print(snap.value) //prints the timestamp
}
The second argument to queryStartingAtValue() is only used to disambiguate between items that match the first argument. To filter by timestamp you should call queryOrderedByChild("timestamp"):
let messagesRef =
FIRDatabase.database().reference().child("all-messages").child(messageId)
.queryOrdered(byChild: "timestamp")
.queryStarting(atValue: 1511130644)

Swift Firebase: Querying Child Nodes without Parent Key

Ok i have the following structure and I wanna pull out all the nodes which contains the registered info.
{
"events" : {
"hsoigjpoirt94pwjfjoijfdg" : {
"coverImageURL" : "http://www.who.int/about/Logo-WHO.jpg",
"dateTime" : "22 May, 2pm",
"eventDescription" : "Lorem ipsum ...",
"eventID" : "hsoigjpoirt94pwjfjoijfdg",
"lat" : 1.2945,
"lon" : 103.8822,
"registered" : {
"NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true
},
"title" : "Volunteer at WHO"
},
"hvasdhpoifah98whfaksad" : {
"coverImageURL" : "http://s3.amazonaws.com/patientslikeme/organizations/11/NKF_D_NEWE_RGB-original.png?1317242994",
"dateTime" : "24 July, 2:30pm",
"eventDescription" : "Lorem ipsum ...",
"eventID" : "hvasdhpoifah98whfaksad",
"lat" : 1.432079,
"lon" : 103.836871,
"registered" : {
"NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true
},
"title" : "Help at Yishun Dialysis"
},
"jioasdifueivaf5262d" : {
"coverImageURL" : "http://www.publichygienecouncil.sg/images/default-source/Photo-Galleries/walk-for-your-kidneys-by-nkf/nkf-litter-picking_25-jan-2014.jpg?sfvrsn=6",
"dateTime" : "12 Feb, 3-6pm",
"eventDescription" : "Lorem ipsum ...",
"eventID" : "jioasdifueivaf5262d",
"lat" : 1.33831,
"lon" : 103.705326,
"title" : "Charity Concert at NKF"
}
},
}
I wanna extract all the snapshots that consist of "registered" with the key "NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true . So far I attempted with the following but it pulls out everything:
ref.child("events").queryOrdered(byChild: "registered").observe(.value, with: { (snapshot) in
let snapValues = snapshot.value as! [String: AnyObject]
print(snapValues)
}) { (error) in
print(error.localizedDescription)
}
FYI, each of these nodes are events where individuals can register to the events. I wanna create view which lists all events a particular user has registered.
Right, just when I was about to give up, I managed to find a solution to get the snaps I want. Here's how I go about doing it:
ref.child("events").queryOrdered(byChild: "registered").observe(.value, with: { (snapshot) in
for snap in snapshot.children {
let snapDataSnapshot = snap as! FIRDataSnapshot
let snapValues = snapDataSnapshot.value as? [String: AnyObject]
if let snapWithReg = snapValues?["registered"] as? [String: Bool] {
if snapWithReg[userUID]! {
print(snap)
}
}
}
}) { (error) in
print(error.localizedDescription)
}
The snaps are all snaps with the 'registered' node and the userUID "NJqoJ4iMTyXGGqfKADoKDLhDYQj1" : true

Querying Firebase with Swift 3.0

I am trying to get all the entries where createdAt is equal to Today, but it returns nothing.
What am I doing wrong here? And, what is the proper way to query data the way I am trying to do?
JSON:
{
"thoughts" : {
"-KWGdcdZD8QJSLx6rSy8" : {
"createdAt" : "Tomorrow",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
},
"-KWGeGivZl0dH7Ca4kN3" : {
"createdAt" : "Today",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
},
"-KWGeIvWHBga0VQazmEH" : {
"createdAt" : "Yesterday",
"thought" : "meno",
"user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2"
}
}
}
Swift:
let db = FIRDatabase.database().reference().child("thoughts")
let ref = db.queryEqual(toValue: "Today", childKey: "createdAt")
ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in
for snap in snapshot.children {
print((snap as! FIRDataSnapshot).key)
}
})
You need to use queryOrderedByChild to createdAt and than use equalTo Today
let ref = FIRDatabase.database().reference().child("thoughts").queryOrdered(byChild: "createdAt").queryEqual(toValue : "Today")
ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in
for snap in snapshot.children {
print((snap as! FIRDataSnapshot).key)
}
})
This is my solution for this JSON:
JSON:
{
"users" : {
"-KWGdcdZD8QJSLx6rSy8" : {
"name" : "dummy1",
"visibility" : true
},
"-KWGeGivZl0dH7Ca4kN3" : {
"name" : "dummy2",
"visibility" : false
},
"-KWGeIvWHBga0VQazmEH" : {
"name" : "dummy3",
"visibility" : true
}
}
}
SWIFT:
//Fetch only Childs with attribute "visibility" = true
Database.database().reference().child("users").queryOrdered(byChild: "visibility").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:Any] else {return}
dictionary.forEach({ (key , value) in
print("Key \(key), value \(value) ")
})
}) { (Error) in
print("Failed to fetch: ", Error)
}
My Solution in Swift 5, Hope this will help.
let ref = Database.database().reference().child("thought")
let refHandle=ref.queryOrdered(byChild:"thoughts").queryEqual(toValue:"Today").observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
let snap = snapshot.value as? [String:Any]
print(snap)
}
})

Accessing son data Firebase

I have a problem, I'm trying to access some data on firebase this is the data structure
I managed to access "favorite"
This is what I used to get
ref.observeEventType(.Value, withBlock: { snapshot in
let fav = snapshot.value.objectForKey("favPost")
print("\(fav) Printed")
})
but I'm trying to access "favPost" but I couldn't figure it out?!!
Firebase structure
{
"posts" : {
"-KGIxJybfQEJbcSy2bHH" : {
"author" : "Rioodi",
"postText" : "Test",
"votes" : 1
},
"-KGIxLUmPIa1Q1k0oRLs" : {
"author" : "Rioodi",
"postText" : "Raed",
"votes" : 0
},
"-KGJe-5ciAyu6Kom98E0" : {
"author" : "Neal",
"postText" : "Neal",
"votes" : 0
},
"-KGLFC0RqW_48lHMCsx8" : {
"author" : "Rioodi",
"postText" : "Test",
"votes" : 0
}
},
"users" : {
"afd0f27a-f62f-4cf1-9e81-032edc246687" : {
"email" : "test#test.com",
"favorite" : {
"-KGIxJybfQEJbcSy2bHH" : {
"favPost" : "Test"
}
},
"provider" : "password",
"username" : "Rioodi"
},
"fc56cc22-6275-48e0-8376-0b73b273b8e2" : {
"email" : "tests#test.com",
"provider" : "password",
"username" : "Neal"
}
}
}
Since you know the userId and you also know you are looking for their favorite post, directly access it like this.
let usersRef = self.myRootRef.childByAppendingPath("users")
let thisUserRef = usersRef.childByAppendingPath("this users id")
let thisUserFavoriteRef = thisUserRef.childByAppendingPath("favorite")
thisUserFavoriteRef.observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
let fav = snapshot.value["favPost"] as! String
print(fav)
})
you could combine the path into a single line as well
let thisUserFavoriteRef = rootRef.childByAppendingPath("users/this users id/favorite")
You can try following code. (you can change according to requirements.)
ref.observeEventType( .Value, withBlock: { snapshot in
//lets consider you have reached up to "favarites"
let favarites = snapshot?.value as! [ String : [ String : AnyObject ] ]
//In "favarites" array you will get whole list
for favarite in favarites
{
let favPost = favarite.1[ "favPost" ] as? String //to access value part
print("\(favPost) Printed"
}
}

Resources