Reputation: 57
I am trying to decode a base64 string to an UIImage in Swift.
The encoded string for my sample image starts with:
data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKC...
The full encoded string can be seen at: base64 string
I use the following function to decode this into an image:
func ConvertBase64StringToImage (imageBase64String:String) -> UIImage {
let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
let image = UIImage(data: imageData!)
return image!
}
If I call that function with the string above as parameter, an error is occuring saying that imageData
is nil (Fatal error: Unexpectedly found nil while unwrapping an Optional value).
What am I doing wrong here?
Upvotes: 2
Views: 1720
Reputation: 318784
That's not a normal base64 encoded string. It's a data URL that starts with data:image/jpeg;base64
.
You want something like:
func ConvertBase64StringToImage (imageBase64String:String) -> UIImage? {
if let url = URL(string: imageBase64String) {
do {
let imageData = try Data(contentsOf: url)
let image = UIImage(data: imageData)
return image
} catch {
print(error)
}
}
return nil
}
Note that you should make this return an optional image to deal with errors.
If you need to handle these types of strings in addition to "normal" base64 encoded strings, you can see if imageBase64String
has the prefix data:
or not and act accordingly.
Upvotes: 8