小编典典

如何在Swift中将base64String转换为String?

swift

我从NSData的Web服务响应中接收到base64String,如何快速将base64String转换为String?

    //Code
    var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary  // Response JSON from webservice
    var base64String : String = ""
    base64String = jsonResult["Base64String"] as! String  // Retrieve base64String as string from json response
    println("Base64String Alone: \(base64String)")

// Code to decode that base64String
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
                                    println("Decoded:  \(decodedData)")
                                    let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
                                    println(decodedString) // Prints nil

如果文件包含某些表格式/图像,则编码和解码都会给出无效的base64String,base64String的编码和解码可以很好地用于仅包含文本的文件。如何将文件转换为base64String进行编码和解码,无论文件内容如何?文件格式为doc,docx,pdf,txt

预先感谢您的任何帮助!


阅读 346

收藏
2020-07-07

共1个答案

小编典典

试试这个

let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="

let decodedData = Data(base64Encoded: base64Encoded)!
let decodedString = String(data: decodedData, encoding: .utf8)!

print(decodedString)

println(decodedString)

确保您的base 64编码字符串有效

2020-07-07