NSDataBase64DecodingOptions返回nil值

时间:2015-04-03 19:53:25

标签: json swift base64 decode

我正在尝试将base64类型解析为imageData。但我的NSDataBase64DecodingOptions返回nil。我打印decodeData,它是零。我的代码在这里

var base64String = arrayText["auto_type_android_img"] as String

println("basestring64 is \(base64String)")

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

println("base string is: \(decodedData)")
if let decodedImage = UIImage(data: decodedData!) {

    imageTypeOfCar?.image = decodedImage
}

1 个答案:

答案 0 :(得分:1)

您的base64String

data:image/png;base64,iVBORw0KGgoA......YII=

初始"data:image/png;base64," 不是 Base64的一部分 编码,必须在解码字符串之前删除:

if let range = base64String.rangeOfString("data:image/png;base64,", options: .AnchoredSearch)  {
    base64String.removeRange(range)
}

然后

let decodedData = NSData(base64EncodedString: base64String, options: nil)
if let decodedImage = UIImage(data: decodedData!) {
    imageTypeOfCar?.image = decodedImage
}

成功并显示

enter image description here