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)

}
Saeed Rahmatolahi
  • 1,317
  • 2
  • 27
  • 60

1 Answers1

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]))

}
Aleksandr Honcharov
  • 2,343
  • 17
  • 30