Swift base64 decoding returns nil

后端 未结 7 898
-上瘾入骨i
-上瘾入骨i 2020-12-15 06:36

I am trying to decode a base64 string to an image in Swift using the following code:

let decodedData=NSData(base64EncodedString: encodedImageData, options: N         


        
7条回答
  •  不思量自难忘°
    2020-12-15 06:47

    When the number of characters is divisible by 4, you need to avoid padding.

    private func base64PaddingWithEqual(encoded64: String) -> String {
      let remainder = encoded64.characters.count % 4
      if remainder == 0 {
        return encoded64
      } else {
        // padding with equal
        let newLength = encoded64.characters.count + (4 - remainder)
        return encoded64.stringByPaddingToLength(newLength, withString: "=", startingAtIndex: 0)
      }
    }
    

提交回复
热议问题