Base64 fast decoding returns nil

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

let decodedData=NSData(base64EncodedString: encodedImageData, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) 

Unfortunately, the decodedData variable turns out to be nil

Debugging through code, I checked that the encodedImageData variable is non-zero and is the correct encoded image data (verified using the base64 online to image converter). What could be causing my problem?

Note. I'm still new to Swift and Xcode

thanks

+6
source share
4 answers

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

In some base64 implementations, a decoding character is not required for decoding, since the number of bytes skipped can be calculated. But in the implementation of the Fund it is necessary.

Updated: As noted in the comments, it is recommended that you first check if the string length is already a multiple of 4. If encoded64 has your base64 string and is not 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) } 

Updated single line version:

Or you can use this version of one line, which returns the same line when its length is already a multiple of 4:

 encoded64.padding(toLength: ((encoded64.characters.count+3)/4)*4, withPad: "=", startingAt: 0) 
+18
source

When the number of characters is divided 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) } } 
+5
source

(Swift 3) I was in this situation. Trying to get data using a base64 encoded string returns zero with me when I used this string

 let imageData = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters) 

Tried to fill in the line and did not work either

This is what worked for me

 func imageForBase64String(_ strBase64: String) -> UIImage? { do{ let imageData = try Data(contentsOf: URL(string: strBase64)!) let image = UIImage(data: imageData) return image! } catch{ return nil } } 
+1
source

Another single line version:

 let length = encoded64.characters.count encoded64 = encoded64.padding(toLength: length + (4 - length % 4) % 4, withPad: "=", startingAt: 0) 
0
source

All Articles