How to convert an PFFile to an UIImage with swift?

2020-01-29 17:04发布

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

3条回答
聊天终结者
2楼-- · 2020-01-29 17:37

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)")
                }
            }
        }
查看更多
Explosion°爆炸
3楼-- · 2020-01-29 17:41

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
                    }

                }
            })
        }
查看更多
戒情不戒烟
4楼-- · 2020-01-29 17:48

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)
         }
      })
}
查看更多
登录 后发表回答