解码base64字符串在swift中出错了 [英] Decoding base64 string is going wrong in swift

查看:1109
本文介绍了解码base64字符串在swift中出错了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文如下:我编写了一个应用程序,可以从库中选择一个图像,然后将图像转换为base64字符串,如下所示:

The context is as follows: I wrote an app which can choose an image from your library and then it converts the image into base64 string as follows:

    let imageData:NSData = UIImageJPEGRepresentation(self.myImageView.image!, 0.1)! as NSData
    let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

这里myImageView是选择图像时存储图像的位置。然后我将它上传到我的本地mysql数据库,其中我有MEDIUMTEXT类型的列。然后我编写了一个可以从数据库中获取此字符串的应用程序,但是当我想要解码它并再次使其成为UIimage时,我的程序失败了。这就是我试过的:

Here myImageView is where the image is stored when one chooses an image. Then I uploaded this into my local mysql database, where I have column of type MEDIUMTEXT. Then I wrote an app that could get this string from the database, but when I wanted to decode it and make it a UIimage again, my program failed. This is what I tried:

    let dataDecoded:NSData = NSData(base64Encoded: tempString64, options: NSData.Base64DecodingOptions(rawValue: 0))!
    let decodedimage:UIImage = UIImage(data: dataDecoded as Data)!

这里tempString64是我从数据库得到的字符串(我还检查过它不是空的) 。如果我运行应用程序,我会在尝试打开它时收到dataDecoded为nil的错误。我真的不明白为什么它是零,而我的临时信息确实存在。

Here tempString64 is the string that I got from the database (I also checked that it is not empty). If I run the app I get an error that dataDecoded was nil while trying to unwrap it. I really don't understand why it is nil, while my tempString is really there.

谢谢。

更新:
我尝试了很多东西,但它没有用!以下是我在URLSession中使用的代码的相关部分:

UPDATE: I tried many things, but it is not working! Here is the relevant part of the code that I use now inside URLSession:

   if data != nil {
            do {
                let imagesJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                let images : NSArray = imagesJSON["images"] as! NSArray
                let temp : NSArray = images[0] as! NSArray
                var tempString64 : String = temp[0] as! String
                // I found a question on this site that said that the string should be of length multiple of 4, the following does that.
                let remainder = tempString64.count % 4
                if remainder > 0 {
                    tempString64 = tempString64.padding(toLength: tempString64.count + 4 - remainder,
                                                  withPad: "=",
                                                  startingAt: 0)
                }
                //check if string is not nil
                print(tempString64)

                let dataDecoded = Data(base64Encoded: tempString64)
                let decodedimage = UIImage(data: dataDecoded!)

               DispatchQueue.main.async {
                    self.myImageView.image = decodedimage
                }

            } catch {
                print(error)
            }
        }

tempString64的尾巴

Tail of tempString64

wBr9KavclvUrxPlNp6ircQ5qNLTDfe/Sr8Vvj L9KqS0BbEM2AKz2rXmt8j736VRNr/ALX6UJEmcv3qnPSpRZ/N979Kn y8fe/SqKiZhNJV1rP/AGv0pPsf 1 lEkJlFhkYpAoQe9aH2Pj736VE1n/t/pTV7DRXjPzVpL0qGCy5yX/StEW2B979KLFrYzpadafxfhU8ltn L9Kktrbbu b07Uraktn/2Q==

tempString64的长度为13752

Length of tempString64 is 13752

推荐答案

该问题是由 lineLength64Characters 选项引起的。如果指定了此选项,则必须使用选项 ignoreUnknownCharacters

The issue is caused by the lineLength64Characters option. If this option is specified you have to decode the data with option ignoreUnknownCharacters

let dataDecoded  = Data(base64Encoded: tempString64, options: .ignoreUnknownCharacters)!






但省略所有选项要容易得多。无论如何,数据库并不关心好的格式。


But it's much easier to omit all options. The database doesn't care about nice formatting anyway.

let strBase64 = imageData.base64EncodedString()

...

let dataDecoded  = Data(base64Encoded: tempString64)!

更新:

删除填充代码并安全地获取编码的字符串。 API为您处理填充。

Remove the padding code and get the encoded string safely. The API handles the padding for you.

不要使用 NSArray NSDictionary 在Swift中,使用本机类型安全类型。并且永远不会使用 .mutableContainers 特别是您将值分配给 im 可变常量。 Swift中的选项毫无意义。

Don't use NSArray and NSDictionary in Swift, use native type safe types. And never ever use .mutableContainers particularly you assign the value to an immutable constant. The option is pointless in Swift.

 if let data = data {
    do {
        if let imagesJSON =  try JSONSerialization.jsonObject(with: data) as? [String:Any],
           let images = imagesJSON["images"] as? [Any],
           let temp = images.first as? [String],
           let tempString64 = temp.first {

           print(tempString64)

           let dataDecoded = Data(base64Encoded: tempString64)
           let decodedimage = UIImage(data: dataDecoded!)

           DispatchQueue.main.async {
               self.myImageView.image = decodedimage
           }
       }

    } catch {
        print(error)
    }
}

这篇关于解码base64字符串在swift中出错了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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