0
votes

I'm trying to retrieve images from Parse as PFFiles but the order in which they are returned changes every time. I found another question/answer that addresses this problem but it's in Obj-C and after an hour, I cannot translate a working solution in Swift.

Here's the original thread:

Parse PFFile download order iOS

And here's my code:

func retrieveItemImage() {

        var query = PFQuery(className: "Items")
        query.orderByDescending("createdAt")
        query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil {
                let imageObjects = objects as! [PFObject]
                for object in imageObjects {
                    let thumbnail = object["image1"] as! PFFile

                    thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
                        if error == nil {
                            if let image = UIImage(data: imageData!) {
                                self.images.append(image)
                                self.theTableView.reloadData()
                            }
                        }
                    }
                }
            }
            self.theTableView.reloadData()
        }

}
1

1 Answers

1
votes

I would make it that way:

var images = [Int: UIImage]()

Make it a dictionary, then you get an optional result of subscript and never have an array out of range exception.

Then I would rewrite the part of your code as:

            for (index, object) in enumerate(imageObjects) {
                let thumbnail = object["image1"] as! PFFile

                thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
                    if error == nil {
                        if let image = UIImage(data: imageData!) {
                            self.images[index] = image

You never know the order of async operations completion, but your images will be in specified order, or nil in dictionary. You should also correct your tableView methods to check it for nil. Also, in my opinion, reloading the whole table after each image loading is ineffective.