Swift Convert string Base64 to UIImage

Refresh

1 weeks ago

Views

1.6k time

1

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?

2 answers

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")
    }
3

Попробуйте не передавать никаких вариантов, я также рекомендую использовать развертку для дополнительных опций:

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")
}