0
votes

I use NSData to convert UIImage from photolibrary to NSData but it gives.

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

Following is my code

if(o.count == 1)
{//o is [UIImage]
    let imgdata:NSData? = UIImageJPEGRepresentation(self.o[0], 10)
    print(o[0]) //it show <UIImage: 0x14e123cb0>, {30, 40}
    print(imgdata)
}
1
If print shows a UIImage (not nil) then the error is somewhere elseLeo Dabus

1 Answers

0
votes

if o.count == 0, the array is empty. So you are trying to create NSData from an empty array here

UIImageJPEGRepresentation(self.o[0], 10)

It's safer to do

if let imgdata = UIImageJPEGRepresentation(self.o[0], 10) {
   ...
}

So your app doesn't crash if it returns nil. Swift knows that UIImageJPEGRepresentation returns NSData, so you don't need the :NSData? in the if statement.

Hope this helps!