1

I'm currently trying to do something fairly simple... just trying to decode then encode an image in Swift 5.

I've been able to see that my image is indeed correct, but it seems like whenever I try to encode the base64 string in Swift, it won't load at all into my UIImageView.

I've run the base64 decoded string in online converters and the image is correctly formatted.

Did I do anything stupid? Thanks so much for any help you can provide!

The Decode Process (currently seems to be working)

let b64 = UIImagePNGRepresentation(tempImage);
var tempImage2 = b64?.base64EncodedString(options: .endLineWithLineFeed);
if (tempImage2 == nil) {
    tempImage2 = "";
}

And the encoding process / loading into the image view:

if let data = Data(base64Encoded: tempImage2!, options: .ignoreUnknownCharacters) {
    var useImage = UIImage(data: data);
    imageView.image = useImage
    print("and now the image view should show it??");
}

On printing the decoded base64, everything seems correct. As soon as I run the encoding, however, nothing is being loaded into my UIImageView - just blankness.

Finn C
  • 217
  • 2
  • 3
  • 9
  • Can you keep in memory the two data? And check if they are equal? If not, might want to print it into String for instance as hex string (see https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift/40089462#40089462) and compare the output? – Larme Jul 29 '20 at 20:39
  • Hi Larme - thanks for the help. The variable definitely isn't nil and the tempImage2 var is indeed in memory. It seems to be the encoding that isn't proper. – Finn C Jul 29 '20 at 20:43
  • I meant keeping `b64` and `data`, and do `print("b64 \(b64 == data ? "=" : !)= data)` Like a quick test: `extension someStructorClass { static var b64: Data?; static var decodedb64: Data?}` and compare them when possible. – Larme Jul 29 '20 at 20:44
  • Oh, I gotcha. Let me run that. – Finn C Jul 29 '20 at 20:45
  • Just tested your code; on my machine it works. Except the compiler complaints that `UIImagePNGRepresentation(tempImage)` should be replaced by `tempImage.pngData()`. – Andreas Oetjen Jul 29 '20 at 20:48
  • Very odd indeed, the hexes are identical, which leads me to believe now there's something wrong with the UIImageView itself. On my end, I get a compiler error on .pngData() as it was replaced with UIImagePNGRepresentation. – Finn C Jul 29 '20 at 20:52

1 Answers1

0

Turns out that the above code works for decoding and encoding base64 in Swift. The issue, however, was with respect to what happened after this code.

Turns out I was messing up some things with the imageView, reusing it as a subview and greatly complicating the process.

Thanks for the help, everyone!

Finn C
  • 217
  • 2
  • 3
  • 9