我试过
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
答案 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。