Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在swift中解码base64字符串出错_Ios_Swift_Image_Base64 - Fatal编程技术网

Ios 在swift中解码base64字符串出错

Ios 在swift中解码base64字符串出错,ios,swift,image,base64,Ios,Swift,Image,Base64,上下文如下:我编写了一个应用程序,可以从库中选择图像,然后将图像转换为base64字符串,如下所示: let imageData:NSData = UIImageJPEGRepresentation(self.myImageView.image!, 0.1)! as NSData let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters) 这里myImageView是在选择图像时

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

    let imageData:NSData = UIImageJPEGRepresentation(self.myImageView.image!, 0.1)! as NSData
    let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
这里myImageView是在选择图像时存储图像的位置。然后我把它上传到我的本地mysql数据库中,在那里我有一个MEDIUMTEXT类型的列。然后我编写了一个应用程序,可以从数据库中获取这个字符串,但是当我想解码它并使它再次成为UIimage时,我的程序失败了。这就是我所尝试的:

    let dataDecoded:NSData = NSData(base64Encoded: tempString64, options: NSData.Base64DecodingOptions(rawValue: 0))!
    let decodedimage:UIImage = UIImage(data: dataDecoded as Data)!
这里tempString64是我从数据库中获得的字符串(我还检查了它是否为空)。如果我运行该应用程序,我会在尝试打开它时收到一个错误,数据解码为零。我真的不明白为什么它是零,而我的临时字符串真的在那里

谢谢

更新: 我尝试了很多东西,但都不管用!下面是我现在在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的尾部

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

tempString64的长度为13752

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

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

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

let strBase64 = imageData.base64EncodedString()

...

let dataDecoded  = Data(base64Encoded: tempString64)!
更新:

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

不要在Swift中使用
NSArray
NSDictionary
,请使用本机类型安全类型。而且永远不要使用
.mutableContainers
,尤其是将值赋给im可变常量。在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)
    }
}

在Swift中使用
Data
而不是
NSData
。您是否将编码数据时得到的字符串与存储在数据库中的字符串以及从数据库中返回的字符串进行了比较?@Paulw11好的,我现在使用数据,仍然不起作用。字符串确实是一样的。为什么要使用“行长度”选项?@Paulw11我认为没有必要,但它在数据库中看起来更好。请显示
tempString64
的长度及其尾部。谢谢您的回答。我想我找到了罪魁祸首:当我更仔细地查看tempString64时,我看到末尾有一个括号。我不确定,但是base64中应该有一个括号吗?顺便说一下,字符串的结尾是:lRt/X7J61CE9II33CE9TRE5QFVUN61LF1RSWKWP ErKH3WrVn 5WSPUTRS2I5OWXQMRSXLNNNPVKY6GRSP3M/Cs57s0RTk5mINWR/qV pqtJ/RJVKF6FQAJBGN/WH6U Ind NNP sP0pYvvD61LBi3f UVE3PWDEQZEKAPJD/69az77/X6VTS2M3SURGAP2Z//)我删除了lineLength选项并添加了lineLength选项.ignoreUnknownCharacters只是为了确定,但它仍然给出相同的错误。它看起来像是字符串插值错误。您是否以
“\(strBase64)”
的形式使用字符串,并且有一个像
“\(strBase64))“
这样的附加右括号?是的,您是对的:)我在那里有一个附加的圆括号。已修复,但数据解码仍然为零:(