How to convert a base64String to String in Swift?(如何在 Swift 中将 base64String 转换为 String?)
问题描述
我在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Swift 中将 base64String 转换为 String?


基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01