UIImagePNGRepresentation(UIImage()) returns nil

Rodrigo Ruiz picture Rodrigo Ruiz · Mar 4, 2015 · Viewed 10.8k times · Source

Why does UIImagePNGRepresentation(UIImage()) returns nil?

I'm trying to create a UIImage() in my test code just to assert that it was correctly passed around.

My comparison method for two UIImage's uses the UIImagePNGRepresentation(), but for some reason, it is returning nil.

Thank you.

Answer

Jojodmo picture Jojodmo · Mar 4, 2015

UIImagePNGRepresentation() will return nil if the UIImage provided does not contain any data. From the UIKit Documentation:

Return Value

A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.

When you initialize a UIImage by simply using UIImage(), it creates a UIImage with no data. Although the image isn't nil, it still has no data. And, because the image has no data, UIImagePNGRepresentation() just returns nil.

To fix this, you would have to use UIImage with data. For example:

var imageName: String = "MyImageName.png"
var image = UIImage(named: imageName)
var rep = UIImagePNGRepresentation(image)

Where imageName is the name of your image, included in your application.

In order to use UIImagePNGRepresentation(image), image must not be nil, and it must also have data.

If you want to check if they have any data, you could use:

if(image == nil || image == UIImage()){
  //image is nil, or has no data
}
else{
  //image has data
}