-1

I have the following swift 3 code in an xcode 8 project:

if pictureImg.image == nil {
  print("image nil")
}

if pictureImg.image != nil {
  print("image not nil")
}

if pictureImg.image != nil {
  imageData = UIImageJPEGRepresentation(pictureImg.image!, 0.5)!
}

At runtime, I end up with a peculiar result in the console:

image not nil
fatal error: unexpectedly found nil while unwrapping an Optional value

And so it appears that my pictureImg.image is in fact nil despite my previous identical if statement saying otherwise. Checks to see whether UIImageJPEGRepresentation is nil also results in the same error:

if UIImageJPEGRepresentation(pictureImg.img!, 0.5) == nil { *code* }

confirming the problem is definitely to do with pictureImg.image, or so it seems.

Is there an immediate/obvious issue with this code or will more information about the project need to be stated?

Legatro
  • 3,692
  • 4
  • 15
  • 21
  • 1
    Are you checking if `UIImageJPEGRepresentation` is returning `nil`? You're force-unwrapping the return value there. Also you should be using `if let` statements instead of checking for `nil`. – JAL Jan 31 '17 at 23:06
  • Never, ever use ! To unwrap optional sin Swift. There are so many nice ways to do it. This is the smash it with big things approach. – Fogmeister Jan 31 '17 at 23:18
  • 1
    @Fogmeister, "optional sin Swift"!?! Now that's a funny typo! – Duncan C Feb 01 '17 at 00:06

1 Answers1

3

I suppose UIImageJPEGRepresentation(pictureImg.image!, 0.5)! returns nil. Check apple documentation. https://developer.apple.com/reference/uikit/1624115-uiimagejpegrepresentation

Do something like this:

if let image = pictureImg.image {
   if let imageRepresentation = UIImageJPEGRepresentation(image, 0.5) {
     ...
   }
}

This way you are not going to have any issues.

Or you can chain them as @Emptyless suggested

if let image = pictureImg.image, let imageRepresentation = UIImageJPEGRepresentation(image, 0.5) {
     ...
}
alecnash
  • 1,750
  • 1
  • 18
  • 42
  • 1
    Please vote to close the question as a duplicate then: [UIImageJPEGRepresentation returns nil](http://stackoverflow.com/questions/29732886/uiimagejpegrepresentation-returns-nil) – JAL Jan 31 '17 at 23:16
  • 2
    You can chain these in 1 if let statement. If you are only interested in that specific combination I think it looks more neat. – Emptyless Jan 31 '17 at 23:16
  • Works like a charm! Apologies for this question if it's dumb, I'm new to this game, and I'm really thankful you guys can help us idiots! – Legatro Jan 31 '17 at 23:39