0

I have a Parse database which has records consisting (among other items) of PFFile items of thumbnail images. The database is read-only and was created successfully using another program. I confirmed that all thumbnails are in Parse. When I try to retrieve the thumbnails using the function shown below, I get the notification before all the images are processed resulting on occasional failures based on the timing of the post-notification processing. How can I ensure that all records are processed?

    func convertPFilesToImages () {
    println("convertPFilesToImages")
    let notification = NSNotification(name: "imagesLoaded", object: self)
    for i in 0 ..< records.count {
        let userImageFile = records[i].icon
        records[i].image = UIImage()
        println("name: \(self.records[i].name) image: \(self.records[i].image)")
        userImageFile.getDataInBackgroundWithBlock {
            (imageData: NSData?, error: NSError?) -> Void in
            if error == nil {
                //println("no error")
                if let imageData = imageData {
                    let image = UIImage(data:imageData)!

                    self.records[i].image = image
                    // println below shows that not all images are converted
                    println("name: \(self.records[i].name) image: \(self.records[i].image)")
                }
            } else {
                println("ParseProcessing-convertToImage: error = \(error)")
            }
            if (i == self.records.count-1) {
                println("All images processed")
                // loop is done before all images are processed
                NSNotificationCenter.defaultCenter().postNotification(notification)
            }

        }
    }

}
0

1 Answer 1

2

Your for() loop executes async code, your problem is with getDataInBackground.

when i == self.records.count-1 it doesn't guarantee all calls have finished up.

getDataInBackround should be as converted to getData (or however Parse named the SYNCHRONOUS call), and your whole method should be called in a background thread.

You could also use a NSOperationQueue to load everything simultaneously, and then call [queue waitUntilFinished].

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the prompt response. I incorrectly assumed that getDataInBackgroundWithBlock helps me. I will try an approach using the synchronous calls inside a background thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.