3

I'm trying to convert base 64 encoded string to UIImage with the following code:

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0) )

print(decodedData) //I get data here (It is not nil)

var decodedimage = UIImage(data: decodedData!) //return nil

The decodedData seems fine, Why do I get nil when converting to UIImage?

3
  • I had a mistake with my question: Commented Oct 9, 2016 at 12:09
  • 1
    If decodedData != nil but decodedimage == nil then the data is not in a valid image format. Commented Oct 9, 2016 at 12:28
  • Hi, you right! It was extra characters at the beginning of the base64 string. Thanks! Commented Oct 10, 2016 at 6:09

2 Answers 2

7

Try to pass no options, I also recommend using unwrap for optionals :

if let string = base64String {
    let decodedData = NSData(base64EncodedString: base64String!, options: []) 
    if let data = decodedData {
        var decodedimage = UIImage(data: data)
    } else {
        print("error with decodedData")
    }
} else {
    print("error with base64String")
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, Thanks, I will try it.
Hi, unfortunately it didn't solve my problem. The program doesn't print any of 2 prints in code. It means that the data is not nil. For some reason, the code refuse to convert the 'data' to UIImage and return nil in that step.
could be a problem with the data you retrieve
Yes, you right. As I mentioned above, I got several characters at the beginning of the Base64 string. After I removed it, the data could be converted to UIImage.
1

For Swift 4.2

if base64String != nil {
        let decodedData = NSData(base64Encoded: base64String!, options: [])
        if let data = decodedData {
            let decodedimage = UIImage(data: data as Data)
            cell.logo.image = decodedimage
        } else {
            print("error with decodedData")
        }
    } else {
        print("error with base64String")
    }

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.