I have a collection that stores posts. Each post has some strings and references to images. I first call getDocuments and within that I call getData to get the corresponding image to a document from the stored reference. At the end I want to append an Object that contains the strings and the UiImages of this post. However, the Object I append contains the strings but the images are empty since it it does not wait on the firebase getData method. How can I make this work, I am fairly new to swift and firebase.
Here is some example code:
query.getDocuments { snapshot, error in
if error == nil{
if let snapshot = snapshot {
for doc in snapshot.documents{
}
var imageUrls = [String]()
imageUrls.append(contentsOf: [doc["imageOne"] as? String ?? "", doc["imageTwo"] as? String ?? "", doc["imageThree"] as? String ?? "", doc["imageFour"] as? String ?? "", doc["imageFive"] as? String ?? ""])
var images = [UIImage]()
for path in imageUrls{
let storageRef = Storage.storage().reference()
let fileRef = storageRef.child(path)
fileRef.getData(maxSize: 5 * 1024 * 1024) { data, error in
if error == nil && data != nil{
if let image = UIImage(data: data!){
images.append(image)
}
}
else{
//handle error
}
}
}
//I want to wait here till the getData method is finished so I dont get the error
// "index error" because images[] is empty
loadedPost.append(LoadedPost(id: doc.documentID, Userid: doc["userID"] as? String ?? "", timestamp: doc["timestamp"] as? String ?? "", imageOne: images[0], imageTwo: images[1], imageThree: images[2], imageFour: images[3], imageFive: images[4]))
}
}
}