Search code examples
iosswiftparse-platformcloudbackground-process

Downloading multiple files in background using Parse


My question: what is the best way to know when the last image has been downloaded, since once all files have been downloaded I need to update the UI.

I am downloading an array of PFFiles from Parse. What I am doing the moment is: getting the array of PFFiles from parse this way

func getAllUserPictures(completion: (imageFiles: [PFFile]) -> Void) {
         guard let id = currentUserID else {
        return
    }

    let query = PFQuery(className: "Profile")
    query.whereKey("objectId", equalTo: id)
    query.includeKey("avatars")
    query.findObjectsInBackgroundWithBlock { profile, error in
        guard let imageFiles = profile?.first?.objectForKey("avatars") as? [PFFile] else {
            return
        }
        completion(imageFiles: imageFiles)
    }
}

After having obtained the imageFile array from the completion handler I do proceed to download them this way:

func getUserPicturesWithBlock(completion: (result: [UIImage]) -> Void) {
    DataManager.sharedInstance.getAllUserPictures { imageFiles in
        for file in imageFiles {
            file.getDataInBackgroundWithBlock({ data, error in
                guard let data = data, let image = UIImage (data: data) else{
                    return
                }

                self.imagesArray.append(image)
            })
        }
    }
}

Solution

  • Have you considered using multiple PFImageView from the ParseUI framework?

    You could assign each of the PFFiles to a PFImageView in the completion of the query and then call loadInBackground on each PFImageView. The PFImageView class automatically handles updating the images once the data has been loaded and this would also update each image as soon as it's fetched rather than waiting for all of them together.

    Alternatively, to keep a similar structure to what you already have, you could use the size of the imageFiles array to tell when they have all been loaded. In the completion of loading each file, you could check if the number of loaded images is equal to the total size of the array.