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)
}
})
Related
I am trying to simply fetch a users favourite maps onto a tableview.
something that i thought would be very basic but turned out to be extremely difficult.
The code here is the best that i have managed so far, Attempting to somehow reference a (users id) with a (yourmaps id) to fetch specific information.
For example. Since the user has made 1 map his favourite(with id (-LpY4XEER-b21hwMi9sp)). I want to look through all maps within root["yourmap"] and only fetch his map onto a tableview.
Firebase
"users" {
"6g55cHXH4begwooHQvO4EKNV3xm1" : {
"photoURL" : "https://firebasestorage.googleap...",
"username" : "lbarri",
"yourmaps" : {
"-LpY4XEER-b21hwMi9sp" : true
}
}
}
"yourmaps": {
"-LpY4XEER-b21hwMi9sp" : {
"author" : {
"photoURL" : "https://firebasestorage.googleapis.com/v...",
"uid" : "6g55cHXH4begwooHQvO4EKNV3xm1",
"username" : "lbarri"
},
"mapmoderators" : {
"6g55cHXH4begwooHQvO4EKNV3xm1" : true
},
"mapphotoURL" : "https://firebasestorage.googleapis...",
"mapusername" : "Hello World"
},
"-LpYo_pQ8zIOGHHlNU1Q" : {
"author" : {
"photoURL" : "https://firebasestorage.googleapis.com/v...3",
"uid" : "RLFK9xnvhccTu2hbNHq0v05J2A13",
"username" : "lbarri"
},
"mapmoderators" : {
"RLFK9xnvhccTu2hbNHq0v05J2A13" : true
},
"mapphotoURL" : "https://firebasestorage.googleapis.com/...",
"mapusername" : "Dream"
}
}
Swift
func getCurrentUserMaps() {
guard let userProfile = UserService.currentUserProfile else { return }
let currentUserId = userProfile.uid
let userRef = Database.database().reference().child("users").child(currentUserId)
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
let root = snapshot.value as? NSDictionary
if let mapsByUser = root!["yourmaps"] as? [String: Bool] {
for (documentId, status) in mapsByUser {
if status {
// Document is true, check for the maps
self.fetchyourmaps(key: documentId, owner: currentUserId)
}
}
}
}) { (error) in
print(error.localizedDescription)
}
}
func fetchyourmaps(key:String, owner:String) {
let yourMapRef = Database.database().reference().child("yourmaps")
yourMapRef.observeSingleEvent(of: .value, with: {snapshot in
let user = snapshot.value as? NSDictionary
if let mapsByUser = user!["mapmoderators"] as? [String: Bool] {
for (userId, status) in mapsByUser {
if userId == owner && status == true {
print("Owner \(owner) manages this \(user)")
var tempYourMap = [YourMapProfile]()
for key in (snapshot.value as? NSDictionary)! {
let childSnapshot = key as? DataSnapshot
let dict = childSnapshot!.value as? [String:AnyObject]
let author = dict!["author"] as? [String:AnyObject]
let uid = author!["uid"] as? String
let username = author!["username"] as? String
let photoURL = author!["photoURL"] as? String
let url = URL(string:photoURL!)
let mapusername = dict!["mapusername"] as? String
let mapphotoURL = dict!["mapphotoURL"] as? String
let mapurl = URL(string:mapphotoURL!)
let userProfile = UserProfile(uid: uid!, username: username!, photoURL: url!, mapPoints: mapPoints!)
let yourmapprofile = YourMapProfile(mapid: childSnapshot!.key as! String, mapauthor: userProfile, mapusername: mapusername!, mapphotoURL: mapurl!)
tempYourMap.append(yourmapprofile)
}
self.yourmaps = tempYourMap
self.tableView.reloadData()
}
}
}
})
}
print("Owner \(owner) manages this \(user)") does print the correct maps onto the console
After that line it is when i cant figure out how to package the information to my tableview.
I have searched everywhere for information on how to retrieve data from Firebase when referencing one root folder to another but i cant find anything helpful. So any link/guide/ tutorial etc would be appreciated and i'll gladly take it from there. Is this at least how you are supposed to do it?
There are a few ways to do this but here's two: Option 1 is to leverage a deep query to get the maps that are this users favorites. The second is to iterate over the users maps and pull each one at a time.
Option 1:
Start with a maps node like this
allMaps
map_0
favorite_of
uid_0: true
uid_3: true
map_user_name: "Larry"
map_1
favorite_of
uid_2: true
map_user_name: "Moe"
map_2
favorite_of
uid_0: true
map_user_name: "Curly"
Then, a deep query to get all the favorite maps of uid_0
func queryToGetMyFavoriteMaps() {
let uid = "uid_0"
let ref = self.ref.child("allMaps")
let path = "favorite_of/" + uid
let query = ref.queryOrdered(byChild: path).queryEqual(toValue: true)
query.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
print(child) //prints the map_0 & map_2 nodes since that's the favorite onces
}
})
}
Option 2
Change up the allMaps node since we won't be doing a query
allMaps
map_0
map_user_name: "Larry"
map_1
map_user_name: "Moe"
map_2
map_user_name: "Curly"
and then the users node will be something like this
users
uid_0
name: "Frank"
favorite_maps:
map_0: true
map_2: true
uid_1
name: "Leroy"
favorite_maps:
map_1: true
and then the code that reads uid_0's favorite_maps node, and gets the keys from that snapshot, and then iterates over them, reading the map nodes one at a time.
func iterateToGetFavoriteMaps() {
let uid = "uid_0"
let userRef = self.ref.child("users").child(uid)
userRef.observeSingleEvent(of: .value, with: { snapshot in
if let mapRefs = snapshot.childSnapshot(forPath: "favorite_maps").value as? [String: Any] {
let mapKeys = mapRefs.keys //note mapKeys is a Dict so we can directly access the keys
for key in mapKeys {
let mapRef = self.ref.child("allMaps").child(key)
mapRef.observeSingleEvent(of: .value, with: { mapSnapshot in
let name = mapSnapshot.childSnapshot(forPath: "mapUserName").value as? String ?? "No Name"
print(name)
})
}
}
})
}
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)
}
})
I have following Firebase query for parsing into my tableView
{
"-LC8fVE90ovEFRQAhhdv" : {
"description" : "Bu grupta arkadaşlar takılsınlar",
"members" : [ "VSVmIF4o0ie2QMIcXdTDTcC8Hq93", "hJgM5tYU45VmjaMTzYAG4Yo3RyD2", "YrLEyhWf9KOIwoK2YN7HrzxpwMc2" ],
"title" : "Takılmaca"
},
"-LC8wUR-11bX5FnjQ6Mk" : {
"description" : "Hello",
"members" : [ "VSVmIF4o0ie2QMIcXdTDTcC8Hq93", "hJgM5tYU45VmjaMTzYAG4Yo3RyD2", "nkwPkD2FeDZZFDnLunTe3D2EuQr2", "YrLEyhWf9KOIwoK2YN7HrzxpwMc2" ],
"messages" : {
"-LC9Pj9krCB4kZnXtXc8" : {
"content" : "Its me",
"senderId" : "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"
},"-LC9Pj9krCB4kasfXtXc8" : {
"content" : "Who are you",
"senderId" : "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"
}
}
I am trying to get content and senderId with following code
var groupMessages = [Message]()
REF_GROUPS.observeSingleEvent(of: .value) { (groups) in
guard let groups = groups.children.allObjects as? [DataSnapshot] else { return }
for group in groups {
let groupss = group.value as? NSDictionary
if let messages = groupss!["messages"] as? [String: Any] {
}
}
handler(groupMessages)
}
However, I could not reach content because of messages object is created by random identifiers (like LC9Pj9krCB4kZnXtXc8) how can I get that content and senderId?
First thing don't ever use NSDictionary or NSArray in Swift it makes the things complex. Secondly just check snapshot.exists() instead of putting a guard for allObjects.
for group in groups should be replace by for child in snapshot.children and the child will be a DataSnapshot itself. See below code:
REF_GROUPS.observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.exists() {
var allMessages: Array<Dictionary<String, String>> = []
for child in snapshot.children {
let childSnapshot = child as! DataSnapshot
guard let dictValue = childSnapshot.value as? Dictionary<String, Any>, let messages = dictValue["messages"] as? Dictionary<String, Any> else {continue}
if let array = Array(messages.values) as? Array<Dictionary<String, String>> {
allMessages.append(contentsOf: array)
}
}
/// All messages into single array
print(allMessages)
/// All senderIds
let senderIds = allMessages.map({$0["senderId"]!})
print(senderIds)
/// Unique senderIds
let uniqueSenderIds = Array(Set(senderIds))
print(uniqueSenderIds)
/// Grouping the senderId with messages
var finalDict: Dictionary<String, [String]> = [:]
for data in allMessages {
guard let senderId = data["senderId"], let content = data["content"] else {continue}
if var oldValue = finalDict[senderId] {
oldValue.append(content)
}
else {
finalDict[senderId] = [content]
}
}
print(finalDict)
/// Inbuilt Dictionary grouping function
let dictionary = Dictionary(grouping: allMessages, by: {$0["senderId"]!})
print(dictionary)
}
Output: allMessages
[["content": "Its me", "senderId": "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"],["content": "Who are you", "senderId": "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"]]
Output: senderIds
["YrLEyhWf9KOIwoK2YN7HrzxpwMc2", "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"]
Output: uniqueSenderIds
["YrLEyhWf9KOIwoK2YN7HrzxpwMc2"]
Output: finalDict
["YrLEyhWf9KOIwoK2YN7HrzxpwMc2": ["Its me", "Who are you"]]
Output: finalDict
["YrLEyhWf9KOIwoK2YN7HrzxpwMc2": [["content": "Its me", "senderId": "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"], ["content": "Who are you", "senderId": "YrLEyhWf9KOIwoK2YN7HrzxpwMc2"]]]
I'm not sure why're you fetching all groups's content but I would like to suggest to get the data by Groups -> GroupId -> messages ref and put a listener for this ref so that app can be notify whenever new message will be received.
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()
})
I tried to convert my code func by func to Swift 3. I have to say that I had fully working project before. Now I have problem where I have no errors and just some warnings but some of the functions are not being executed. What should cause this?
I only assume that those given functions are faulty because these are the parts where I am not getting anything even print.
These are some of my functions that worked before but not with Swift 3:
//With this I get selected brand products values like product name, nicotine, flavor etc..
let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
if let products = (snapshot.value as AnyObject).allValues as? [[String:AnyObject]]{
self.productsValue = products
self.productsTable.reloadData()
}
}
})
//With this fucntion I get the products count.
let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: filteredBrands[indexPath.row])
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
if let products = (snapshot.value as AnyObject).allValues as? [[String:AnyObject]]{
var count = (snapshot.childrenCount)
snusProductCountLabel.text = "\(count) products"
}
}
})
//Parse snus brands
func parseSnuses(){
let ref = FIRDatabase.database().reference().child("Brands").queryOrderedByKey()
ref.observe(.childAdded, with: { (snapshot) in
self.brands.append(snapshot.key)
print(snapshot.key)
self.snusBrandsTableView.reloadData()
}){ (error) in
}
Anything I can do different please tell me! Those functions are in different ViewControllers.
Edit: this is my JSON tree
{
"Snuses" : {
"Catch Eucalyptus White Large" : {
"Brand" : "Catch",
"Products" : "Catch Eucalyptus White Large",
"PorionWeight" : 21.6,
"flavor" : "Tobacco, Eucalyptus",
"nicotine" : 8.0,
"PortionsCan" : 24,
"shipping weight" : 39
},
And these are security rules:
{
"rules": {
".read": "true",
".write": "true",
"Snuses": {
".indexOn": "Brand"
}
}
}
I believe the
if let products = (snapshot.value as AnyObject)
.allValues as? [[String:AnyObject]]{
is the issue.
Try this as a test to see if it prints the data from the snapshot:
let ref = FIRDatabase.database().reference().child("Snuses")
.queryOrdered(byChild: "Brand").queryEqual(toValue: brandName)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
let dict = snapshot?.value as! [String: [String:String]]
let productsArray = Array(dict)
for row in productsArray {
print(row)
}
}
})
for a non-swifty test, you can also try this inside the closure instead of the above
let d2 = snapshot?.value as! NSDictionary
let a2 = d2.allValues
for r2 in a2 {
print(r2)
}
one more option:
let q = snapshot?.value as! [String: AnyObject]
let a3 = Array(q)
for r3 in a3 {
print(r3)
}
I don't know what your tableView is expecting in the array but one of those should cover it.