Reputation: 402
Need help trying to read an array of this form:
As far as I tried, I got this
let defaults = UserDefaults.standard
let userUuid = defaults.string(forKey: defaultsKeys.keyOne)
let ref = FIRDatabase.database().reference().child("images").child("\(userUuid!)")
let filterQuery = ref.queryOrdered(byChild: "uuid").queryEqual(toValue: "\(uuid)") // where uuid is a value from another view
filterQuery.observe(.value, with: { (snapshot) in
for images in snapshot.children {
print(images)
}
})
But I receive nothing. I want to read the images' links to show them in the view controller.
Upvotes: 0
Views: 2453
Reputation: 402
After strugling for the answer, got this code works
let ref = FIRDatabase.database().reference().child("images").child("\(userUuid!)")
let filterQuery = ref.queryOrdered(byChild: "identifier").queryEqual(toValue: "\(identifier)")
filterQuery.observe(.value, with: { (snapshot) in
for child in snapshot.children {
if (child as AnyObject).hasChild("images") {
let images = (images as AnyObject).childSnapshot(forPath: "images").value! as! NSArray
for i in images {
for j in i as! [AnyObject] {
let url = NSURL(string: j as! String)
//Then downloaded the images to show on view
URLSession.shared.dataTask(with: url! as URL, completionHandler: { (data, response, error) in
if error != nil {
print(error)
return
}
//Code to show images..
}).resume()
}
}
}
}
})
Can i receive feedback about this?
Upvotes: -1
Reputation: 1504
Make sure that the uuid
var in the line below is not an optional value (or if it is, unwrap it) because otherwise you'll be querying to compare to "Optional(myUuidValue)"
instead of "myUuidValue"
let filterQuery = ref.queryOrdered(byChild: "uuid").queryEqual(toValue: "\(uuid)")
The snapshot
in the line below contains more than just the images, it has all the other children under that uuid
filterQuery.observe(.value, with: { (snapshot) in })
So extract the images like this:
filterQuery.observe(.value, with: { (snapshot) in
let retrievedDict = snapshot.value as! NSDictionary
let innerDict = retrievedDict["KeyHere"] as! NSDictionary // the key is the second inner child from images (3172FDE4-...)
let imagesOuterArray = userDict["images"] as! NSArray
for i in 0 ..< imagesOuterArray.count {
let innerArray = imagesOuterArray[i] as! NSArray
for image in innerArray {
print(image as! String)
}
}
})
Clarification: cast all the children of the uuid as an NSDictionary
, then extract the nested arrays using those two for-loops
Update Thanks to Jay for pointing out the error! Also, as Jay suggested, consider restructuring your database and replacing those arrays with dictionaries that perhaps contain the URL, path (for deleting purposes if you need that), and timestamp of each image.
Upvotes: 3