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
}
UIImagePNGRepresentation(UIImage())
, or isUIImage()
just the placeholder for an already created UIImage? – Interlanguage= UIImage()
. Then later I do a comparison between this property and some other UIImage. This comparison is done viaUIImagePNGRepresentation(image1) == UIImagePNGRepresentation(image2)
– Respectability