Managing profile picture of subclassed PFUser with PFFile - Swift / iOS

192 views Asked by At

I've subclassed PFUser in my iOS app and I'm using this function to grab the profile picture. profilePicture is the @NSManaged PFFile and profilePictureImage is a UIImage.

This works great except for the fact that getData() and fetchIfNeeded() are potential long running operations on the main thread.

Can anyone think of a good way to implement this method so the scary parts run on a background thread?

Thanks!

func image() -> UIImage!
{
    if !(self.profilePictureImage != nil)
    {
        if self.profilePicture != nil
        {
            self.fetchIfNeeded()
            if let data = self.profilePicture!.getData() {
                self.profilePictureImage = UIImage(data: data)
                return self.profilePictureImage
            }
        }else {
            return UIImage(named: "no_photo")!
        }
    }
    return self.profilePictureImage
}
2

There are 2 answers

0
Wain On

Change the method so that rather than returning an image it takes a closure which is called when the image is available and passes it as a parameter. This may be called immediately or after some delay if the image needs to be downloaded.

0
oyalhi On

Just do it as you say, run the task in the background using: fetchIfNeededInBackgroundWithBlock. Also, your image function should look something like this:

func imageInBackgroundWithBlock(block: ((UIImage?, NSError?) -> Void)?) {
    var image: UIImage?

    self.fetchIfNeededInBackgroundWithBlock({ (user, error) -> Void in 
        if error == nil {
            // load the picture here
            image = ...

        } else {
            println(error!.userInfo)
            image = UIImage(named: "no_photo")!
        }

        // return after fetching the user and the image
        block?(image, error)
    })

}