Swift base64 解码返回 nil

编程入门 行业动态 更新时间:2024-10-07 18:29:50
本文介绍了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

本文发布于:2023-11-26 23:34:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!