Olyve
Olyve

Reputation: 731

Attempting to check if PFFile has data or not

I am attempting to check if a PFFile has data before it attempts to pull the image from the background. I am attempting this because I keep getting a fatal crash if you try and open one of the objects and there is no image! My problem is that I can't get the data check to work. PFFile != nil does not work and you can't check if it exists with if (recipeImageData) because PFFile does not conform to the boolean protocol. Any help would be appreciated!

Here is the declaration of the variable:

var recipeImageData: PFFile = PFFile()

And here is the function for fetching the data:

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  recipeImageData = recipeObject["Image"] as PFFile //Fatally crashes on this line
  // Fetch the image from the background
  if (recipeImageData) {
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}

EDIT:

I just tried this seeing that I probably am making a check in the wrong area. Here is my updated code.

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  if let recipeImageData = recipeObject["Image"] as? PFFile {
    // Fetch the image in the background
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}

Upvotes: 2

Views: 638

Answers (1)

Olyve
Olyve

Reputation: 731

This check actually works just fine, there was another issue that was causing the crash. The correct code is posted below:

override func viewWillAppear(animated: Bool) {
  navItem.title = recipeObject["Name"] as? String
  if let recipeImageData = recipeObject["Image"] as? PFFile {
    // Fetch the image in the background
    recipeImageData.getDataInBackgroundWithBlock({
      (imageData: NSData!, error: NSError!) -> Void in
      if error == nil {
        self.recipeImage.image = UIImage(data: imageData)?
      } else {
        println("Error: \(error.description)")
      }
    })
  }
}

Upvotes: 6

Related Questions