Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift base64 decoding returns nil

Tags:

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)

Unfortunately, the variable decodedData turns out to have a value of nil

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?

like image 943
redamakarem Avatar asked Apr 01 '16 19:04

redamakarem


2 Answers

This method requires padding with “=“, the length of the string must be multiple of 4.

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.

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:

Swift 2

let remainder = encoded64.characters.count % 4
if remainder > 0 {
    encoded64 = encoded64.stringByPaddingToLength(encoded64.characters.count + 4 - remainder,
                                                  withPad: "=",
                                                  startingAt: 0)
}

Swift 3

let remainder = encoded64.characters.count % 4
if remainder > 0 {
    encoded64 = encoded64.padding(toLength: encoded64.characters.count + 4 - remainder,
                                  withPad: "=",
                                  startingAt: 0)
}

Swift 4

let remainder = encoded64.count % 4
if remainder > 0 {
    encoded64 = encoded64.padding(toLength: encoded64.count + 4 - remainder,
                                  withPad: "=",
                                  startingAt: 0)
}

Updated one line version:

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)
like image 95
jlasierra Avatar answered Sep 23 '22 19:09

jlasierra


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)
  }
}
like image 30
k-yamada Avatar answered Sep 22 '22 19:09

k-yamada