0

I have an array of images in my codes that are [UIImage] but I want to convert them to base64 - I couldn't ! - I found similar questions but when I used their answers I received Fatal Error

for i in  0...tinyViewController.imageUpload.count - 1 {
        print(i)


        let imageData = UIImageJPEGRepresentation(tinyViewController.imageUpload[i] , 1)

        let base64String = (imageData! as Data).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        print(base64String)

}
2
  • can you post the error? Commented Jul 29, 2017 at 12:51
  • fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) Commented Jul 29, 2017 at 12:57

1 Answer 1

1

Try this function to convert each UIImage to base64 String. I used it in my project. It works perfect for me.

func base64(from image: UIImage) -> String? {
        let imageData = UIImagePNGRepresentation(image)
        if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
            return imageString
        }
        return nil
    }

So, do this:

for i in  0...tinyViewController.imageUpload.count - 1 {
        print(i)

        print(base64(from: tinyViewController.imageUpload[i]))

}
Sign up to request clarification or add additional context in comments.

10 Comments

this method will not execute because my images are in an array in a for loop and I should use them in this method but swift doesn't let me to use that ?
I updated my answer. Insert my function and change your code as I wrote.
Again I received fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
Maybe the error in another place of your code? There is no force unwrapping in my code.
where should be the function that you write ? before loop or after loop or inside that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.