Reputation: 21
Below is a section of a query I am attempting to accomplish in Swift.
What I can't grasp is why :
room = Room(images: images, name: name)
rooms.append(room)
runs before:
imageQuery.getDocuments()
{
(QuerySnapshot, err) in
if let err = err{}
else
{
for document in QuerySnapshot!.documents
{
let imageURL = document.data()["imageURL"] as? String ?? ""
let image = ImageModel(imageURL: imageURL, date: Date(timeIntervalSinceNow: 0))
images.append(image)
}
The second snippet of code does run, but it runs after the first snippet. But I need the values from the second one to populate the values in the first. I'm not new to programming but I am new to swift and I cannot seem to figure out how to make the outer loop go into the inner loop before running the rest of its' code. Thank you for your help!
Here is the majority of the function:
let roomQuery = projectRef.document(document.documentID).collection("Rooms")
roomQuery.getDocuments()
{
(QuerySnapshot, err) in
if let err = err{}
else
{
var room:Room
for document in QuerySnapshot!.documents
{
let name = document.data()["name"] as? String ?? ""
var images = [ImageModel]()
let imageQuery = roomQuery.document(document.documentID).collection("Images")
imageQuery.getDocuments()
{
(QuerySnapshot, err) in
if let err = err{}
else
{
for document in QuerySnapshot!.documents
{
let imageURL = document.data()["imageURL"] as? String ?? ""
let image = ImageModel(imageURL: imageURL, date: Date(timeIntervalSinceNow: 0))
images.append(image)
}
}
}
room = Room(images: images, name: name)
rooms.append(room)
}
}
Upvotes: 0
Views: 33
Reputation: 500
because you're using a closure, not a loop, so it is executed asynchronoulsy
Upvotes: 1