In app development, you may need to display an image from the Base64 encoded string in SwiftUI. Well, it can be easily done using the UIImage
with the Image()
view of SwiftUI.
I hope you already know how to show an image by providing the image name to the Image()
view. But, to show the image from a given Base64 encoded string, we are not going to provide any image name as we don’t have it. Here need to provide Base64 encoded string. But we can’t do it directly like providing an image name. There is a different technique that we have to follow using the UIImage()
.
Let’s see how we can achieve showing up an image from Base64:
let base64String = "Base64_STRING"
Image(uiImage: UIImage(data: Data(base64Encoded: base64String)!)!)
That’s it. Now we can see the image in our app.
You can also create an extension of SwiftUI Image that can be used to convert Base64 to an image in SwiftUI. In this way, you have to write the main program only once and use it multiple times whenever the conversion is needed.
Below is how it can be done:
extension Image {
init?(base64Str: String) {
guard let data = Data(base64Encoded: base64Str) else { return nil }
guard let uiImg = UIImage(data: data) else { return nil }
self = Image(uiImage: uiImg)
}
}
Below is how we can use the extension:
Image(base64Str: imgString)