Swift base64 解码返回 nil [英] Swift base64 decoding returns nil

查看:83
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆