I'm appending all of the images to an array when the view loads. I do this by looping through it as so...
func refresh() {
print("View appeared")
self.posts.removeAll(keepCapacity: false)
let postQuery = PFQuery(className: "Post")
postQuery.whereKey("type", equalTo: "world")
postQuery.orderByDescending("createdAt")
postQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects as? [PFObject] {
self.posts = objects
if error == nil {
if self.posts.isEmpty == false {
for post in self.posts {
post["image"]?.getDataInBackgroundWithBlock({ (data, error) -> Void in
if let image = UIImage(data: data!) {
self.images.append(image)
if self.posts.count == self.images.count {
self.table.reloadData()
}
}
})
}
}
}
}
})
}
The problem with this is that it doesn't append the images in the right order. I'm pretty sure this is because it takes a little bit to get the image data and turn into a UIImage, and in that time it just goes onto the next one. I'm not sure if that's what's really going on or not. But what can I do to fix this?
This happens bc you get every image in its own background thread, and the time each takes might vary. So there is no guarantee in which order the threads finish. Also, with this method you are performing lots of requests to Parse.
When retrieving the posts from parse, include this before executing the query:
query.includeKey("image")
Then (just a quick example, not really proof-read...):
for post in self.posts {
if let image = UIImage(post["image"]) {
self.images.append(image)
}
}
self.table.reloadData()