如何在Swift中将base64String转换为String? [英] How to convert a base64String to String in Swift?
问题描述
我正在从NSData中的Web服务响应中接收到base64String,如何快速将base64String转换为String?
I am receiving a base64String from webservice response in NSData, how to convert that base64String to String in swift?
//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
Encode and decode of base64String works well for the files containing only text, if a file contains some table formats/images both encoding and decoding gives an invalid base64String. How to convert a file into base64String encode and decode whatever the contents of file ? File formats are doc, docx, pdf, txt
预先感谢您的帮助!
推荐答案
尝试一下
let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="
let decodedData = Data(base64Encoded: base64Encoded)!
let decodedString = String(data: decodedData, encoding: .utf8)!
print(decodedString)
println(decodedString)
确保您的base 64编码字符串有效
make sure your base 64 encoded string is valid
这篇关于如何在Swift中将base64String转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!