GetDataInBackgroundWithBlock | imageData 返回一个 nil 值

GetDataInBackgroundWithBlock | imageData is returning a nil value

所以我使用解析将一些对象保存到 localDatastore。

//Pin the objects here!!
var imageObject = PFObject(className: "img")
imageObject["theFile"] = imageFile
imageObject.pinInBackgroundWithBlock({ (success, error) -> Void in
   if error == nil {
        imageObject.saveEventually()
        println("object pinned in background")
   } else {
        println(error)
   }
})

然后在 viewDidLoad 中查询对象并将它们附加到 PFFile 的数组中

var query = PFQuery(className: "img")
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
   if error == nil{
        var objects : AnyObject = objects as! AnyObject
        for object in objects as! [AnyObject]{
            self.testImages.append(object["theFile"] as! PFFile)
        }
   } else {
       println(error)
   }
}

此数组现在包含数据。我正在尝试将图像插入 tableView

if testImages.count >= 1{
     testImages[indexPath.row].getDataInBackgroundWithBlock({ (imageData, error) -> Void in
        if error == nil{
           //The app crashes here ~ fatal error: unexpectedly found nil while unwrapping an Optional value
           cell.theImage.image = UIImage(data: imageData!)
         } else {
            println(error)
         }
    })
}

因为你用的是tableview,我觉得最好的办法是从Parse中下载所有的图片,然后保存到一个数组中。然后在 cellForRowAtPath 方法中将该数组的每个索引分配给 cell.imageView.image

 var query = PFQuery(className:"img")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
    if error == nil
    {
        if let objects = objects as? [PFObject]
        {
            for one in objects 
           {
               var pictureImage = one["theFile"] as! PFFile
                pictureImage.getDataInBackgroundWithBlock({ (dataToget:NSData?, error:NSError?) -> Void in
                    if error == nil 
                    {
                   if let  Image = UIImage(data: dataToget)
                     {
                        // save the image to array 
                        // reload the tableview
                      }
                    }
               })

             }
         }
    }
}