I'm new to asynchronous coding and am wondering if the method I'm using to fetch and display data is considered correct in swift.
This method gets a list of objects from a user's section in the database, then fetches a picture for each item in the list. The way I'm telling if all images have been fetched is pushing them to an array as they arrive, then if that array's length is equal to the list of objects I reload the view. Here is my code:
var pets = [String]()
var imgs = [UIImage]()
override func viewDidAppear(_ animated: Bool) {
imgsLoaded = 0
imgs.removeAll(keepingCapacity: false) // Clear images array
pets.removeAll(keepingCapacity: false) // Clear list of objects
let userRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("pets")
userRef.observeSingleEvent(of: .value, with: { snapshot in // fetch list of objects from database
if (snapshot.value as? Bool) != nil { // User has no pets added
self.loadScrollView() // Reload view
} else if let snap = snapshot.value as? NSDictionary { // User has pets
for value in snap {
self.pets.append(value.key as! String) // Append object to list of objects
}
for i in 0..<self.pets.count { // For each item in the list, fetch its corresponding image
let imgRef = FIRStorage.storage().reference().child("profile_images").child(self.pets[i]+".png")
imgRef.data(withMaxSize: 15 * 1024 * 1024) { (data, error) -> Void in
if error != nil {
print(error)
}
// Create a UIImage, add it to the array
self.imgs.append(UIImage(data: data!)!) // Push image to list of images
self.imgsLoaded+=1
if self.imgsLoaded == self.pets.count { // If same number of images loaded, reload the view
self.loadScrollView()
}
}
}
}
})
}
As I said, I'm new to asynchronous coding and would like to hear what the proper way of doing what I'm attempting. One problem with my method is the images array might not align with the data array since an image can be fetched out of order. I'd love to learn the best way to do this so let me know please!
Edit: A way to make sure my data lines up with the corresponding images is to set a dictionary of sorts with the key being the data and the value being the image I guess.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…