Parse-sdk-ios-osx: How to convert PFFile to Uiimage in Swift 3

Created on 13 Jan 2017  路  3Comments  路  Source: parse-community/Parse-SDK-iOS-OSX

Hi ,
I want to convert PFFile to Uiimage
I'm trying to use

if let userPicture = object.valueForKey("Image")! as! PFFile {
   userPicture.getDataInBackgroundWithBlock({
      (imageData: NSData!, error NSError!) -> Void in
         if (error == nil) {
            let image = UIImage(data:imageData)
            self.ImageArray.append(image)
         }
      })
}

but I got error in swift 3

Most helpful comment

Here is my solution within my own app, using Swift 3.2 and Xcode 8.3.1:

DispatchQueue.global(qos: .userInteractive).async {
   // Async background process

   if let imageFile : PFFile = somePFFile {
            imageFile.getDataInBackground(block: { (data, error) in
            if error == nil {
                  DispatchQueue.main.async {
                      // Async main thread

                      let image = UIImage(data: data!)
                      self.imageViewToSet.image = image
                  }
            } else {
                 print(error!.localizedDescription)
            }
       })
    }
}

What @cyring mentioned above about threading is important. Make sure to handle your network calls on a background thread and always update the UI on the main thread.

All 3 comments

I solved my problem

Swift 3

if let userPicture = object.valueForKey("Image")! as! PFFile {
userPicture.getDataInBackground({ (imageData: Data?, error: Error?) -> Void in
let image = UIImage(data: imageData!)
if image != nil {
self.imageArray.append(image!)
 }
 })
}

but I don't know how to access the Image outside the Block
The imageArray empty outside Block , but have value inside Block =\

Set the image in the main thread

Here is my solution within my own app, using Swift 3.2 and Xcode 8.3.1:

DispatchQueue.global(qos: .userInteractive).async {
   // Async background process

   if let imageFile : PFFile = somePFFile {
            imageFile.getDataInBackground(block: { (data, error) in
            if error == nil {
                  DispatchQueue.main.async {
                      // Async main thread

                      let image = UIImage(data: data!)
                      self.imageViewToSet.image = image
                  }
            } else {
                 print(error!.localizedDescription)
            }
       })
    }
}

What @cyring mentioned above about threading is important. Make sure to handle your network calls on a background thread and always update the UI on the main thread.

Was this page helpful?
0 / 5 - 0 ratings