Swift将字符串Base64转换为UIImage

问题描述 投票:1回答:2

我正在尝试使用以下代码将base 64编码的字符串转换为UIImage

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

decodedData似乎很好,为什么我转换到nil时会得到UIImage

ios swift uiimage base64
2个回答
4
投票

尝试不传递任何选项,我还建议使用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")
}

1
投票

对于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")
    }
© www.soinside.com 2019 - 2024. All rights reserved.