NSData base64Encode返回nil swift

时间:2016-05-30 14:33:03

标签: ios swift base64

我试过

let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents, 
options:NSDataBase64DecodingOptions())
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)





let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)



let contents = results["contents"] as! String!
let decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions(rawValue: 0)!)
let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)

始终来自decodeString的EXC_BAC_INSTRUCTION 也许decodeData返回nil

为什么NSData返回nil

2 个答案:

答案 0 :(得分:0)

使用.Encoding64CharacterLineLength作为选项,并将.base64EncodedStringWithOptions应用于数据:

if let contents = results["contents"] as? String,
        decodedData = NSData(base64EncodedString: contents, options:NSDataBase64DecodingOptions(rawValue: 0)) {
    let decodedString = decodedData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}

答案 1 :(得分:-1)

您正在使用如此多的强制解包运算符(!);不要这样做!

如果results没有"contents"密钥的映射,该怎么办?

如果results包含"contents"密钥的映射但它不是String会怎样?

如果results具有"contents"密钥的映射,并且它是String,但它不是有效的Base 64编码数据,该怎么办?在这种情况下,NSData的初始化将失败,并返回nil。