问题描述
我正在尝试使用以下代码将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)