GetDataInBackgroundWithBlock | imageData返回一个nil值

时间:2015-08-27 14:53:27

标签: ios objective-c swift null

所以我使用parse将一些对象保存到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)
         }
    })
}

1 个答案:

答案 0 :(得分:0)

因为您正在使用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
                      }
                    }
               })

             }
         }
    }
}