简体   繁体   中英

How to convert an PFFile to an UIImage with swift?

How do i convert an PFFile to an UIImage with swift?

In this code, the app is getting the file from parse and now i want it to show on a UIImageView, But i get an error...

Here is my code...

 var ImageArray:UIImage = [UIImage]()
    var textArray:String = [String]()

     var query = PFQuery(className:"ClassName")

            query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]?, error: NSError?) -> Void in

                if error == nil {


                    if let objects = objects as? [PFObject] {
                        for object in objects {
     //this works fine                       
self.textArray.append(object.valueForKey("Image")! as! String)



    //this does not work...
                            self.ImageArray.append(object.valueForKey("Image")! as! PFFile)
    //I get an error that says PFFile is not convertible to UIImage. How do i convert it?






                        }
                    }
                } else {
                    // Log details of the failure
                    println("Error: \(error!) \(error!.userInfo!)")
                }

PFFile is a parse representation of anykind of file. To get the "real" file (image), you need to call getDataInBackgroundWithBlock . Try it:

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)
         }
      })
}

Swift 1.2+ Version

        if let userPicture = PFUser.currentUser()!.valueForKey("Image") as? PFFile {
            userPicture.getDataInBackgroundWithBlock {
                (imageData: NSData?, error: NSError?) -> Void in

                if error == nil {
                    let image = UIImage(data:imageData!)
                    self.ImageArray.append(image)
                }else{
                    print("Error: \(error)")
                }
            }
        }

With Swift 3 on Parse.

  if let photo = obj.file as? PFFile {
       photo.getDataInBackground(block: {
          PFDataResultBlock in
          if PFDataResultBlock.1 == nil {//PFDataResultBlock.1 is Error
                    if let image = UIImage(data:PFDataResultBlock.0!){
                        //PFDataResultBlock.0 is Data
                        photoCell.attachedPicture.image = image
                    }

                }
            })
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM