Swift base64 decoding returns nil(Swift base64 解码返回 nil)
问题描述
我正在尝试使用以下代码将 base64 字符串解码为 Swift 中的图像:
I am trying to decode a base64 string to an image in Swift using the following code:
let decodedData=NSData(base64EncodedString: encodedImageData, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
不幸的是,变量 decodedData 的值为 nil
Unfortunately, the variable decodedData turns out to have a value of nil
通过代码调试,我验证了变量 encodedImageData 不是 nil 并且是正确的编码图像数据(通过使用在线 base64 到图像转换器进行验证).我的问题背后的原因可能是什么?
Debugging through the code, I verified that the variable encodedImageData is not nil and is the correct encoded image data(verified by using an online base64 to image converter). What could possibly be the reason behind my issue?
推荐答案
此方法需要用="填充,字符串长度必须是4的倍数.
This method requires padding with "=", the length of the string must be multiple of 4.
在 base64 的某些实现中,解码不需要填充字符,因为可以计算丢失字节的数量.但在 Fundation 的实施中,这是强制性的.
In some implementations of base64 the padding character is not needed for decoding, since the number of missing bytes can be calculated. But in Fundation's implementation it is mandatory.
更新:如评论中所述,最好先检查字符串长度是否已经是 4 的倍数.如果 encoded64 具有您的 base64 字符串并且它不是常量,则可以执行以下操作:
Updated: As noted on the comments, it's a good idea to check first if the string lenght is already a multiple of 4. if encoded64 has your base64 string and it's not a constant, you can do something like this:
斯威夫特 2
let remainder = encoded64.characters.count % 4
if remainder > 0 {
encoded64 = encoded64.stringByPaddingToLength(encoded64.characters.count + 4 - remainder,
withPad: "=",
startingAt: 0)
}
斯威夫特 3
let remainder = encoded64.characters.count % 4
if remainder > 0 {
encoded64 = encoded64.padding(toLength: encoded64.characters.count + 4 - remainder,
withPad: "=",
startingAt: 0)
}
斯威夫特 4
let remainder = encoded64.count % 4
if remainder > 0 {
encoded64 = encoded64.padding(toLength: encoded64.count + 4 - remainder,
withPad: "=",
startingAt: 0)
}
更新了一行版本:
或者你可以使用这一行版本,当它的长度已经是 4 的倍数时返回相同的字符串:
Or you can use this one line version that returns the same string when its length is already a multiple of 4:
encoded64.padding(toLength: ((encoded64.count+3)/4)*4,
withPad: "=",
startingAt: 0)
这篇关于Swift base64 解码返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift base64 解码返回 nil


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