2

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?

3
  • How is the original string generated? Commented Oct 6, 2018 at 0:10
  • Drop the first 27 characters from your string before passing it to this function. Commented Oct 6, 2018 at 0:21
  • 1
    @Carpsen90 Or use the string as-is with the correct code (see my answer). Commented Oct 6, 2018 at 0:22

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.