10

A web service echoes a Base64 encoded image as a string. How can one decode and display this encoded image in a Swift project?

Specifically, I would like to take an image, which is already provided by the web service as a string in Base64 format, and understand how to display it in a UIImageView.

The articles I have found thus far describe deprecated techniques or are written in Objective-C, which I am not familiar with. How do you take in a Base64-encoded string and convert it to a UIImage?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Voccola
  • 1,827
  • 6
  • 20
  • 46

2 Answers2

33

Turn your base64 encoded string into an NSData instance by doing something like this:

let encodedImageData = ... get string from your web service ...
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros)

Then turn the imageData into a UIImage:

let image = UIImage(data: imageData)

You can then set the image on a UIImageView for example:

imageView.image = image
Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
3

To decode Base64 encoded string to image, you can use the following code in Swift:

let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
var decodedimage = UIImage(data: decodedData)
println(decodedimage)
yourImageView.image = decodedimage as UIImage

Even better, you can check if decodedimage is nil or not before assigning to image view.

Raptor
  • 53,206
  • 45
  • 230
  • 366