Converting UIImage to Base64 string and back in Swift
Hello everyone! I'm a beginner in Swift and iOS development. I'm writing an app that should send an image to the server as a Base64 string, then receive it back and display it. But I'm having problems with the conversion.
Here's what I'm trying:
```swift
// Converting UIImage to Base64
let image = UIImage(named: "photo.jpg")
let imageData = UIImageJPEGRepresentation(image!, 0.5)
let base64String = imageData?.base64EncodedString(options: .lineLength64Characters)
print(base64String ?? "No data")
```
But an empty string or incorrect data arrives at the server. When I try to decode it back:
```swift
// Converting Base64 back to UIImage
let decodedData = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
```
No answers yet.
Log in to leave an answer
Blogs