UIImagePNGRepresentation() will return nil if the provided UIImage does not contain any data. From the UIKit Documentation :
Return value
A data object containing PNG data, or nil if there is a problem generating data. This function can return zero if the image has no data , or if the underlying CGImageRef contains data in an unsupported raster format.
When you initialize UIImage simply using UIImage() , it creates a UIImage without data. Although this is not nil , it still has no data, so it UIImagePNGRepresentation() cannot return data, forcing it to return nil .
To fix this, you will need to use UIImage with the data. For instance:
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.
To use UIImagePNGRepresentation(image) , image must not be nil , and it must have data ( UIImage() creates an image that is not nil , but does not contain any data).
If you want to check if they have any data, you can use:
if(image == nil || image == UIImage()){ //image is nil, or has no data } else{ //image has data }
source share