Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initWithBase64EncodedString return nil

My resultString is 'PHNhbWxwOlJlc3BvbnNlIH...c3BvbnNlPgoK' and when i am decoding it shows me decodedData as nil.

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:resultString options:0];

I also tried this string with https://www.base64decode.org/ , it successfully shows results.

What wrong here in decoding ?

like image 769
Krish Solanki Avatar asked Jun 16 '17 10:06

Krish Solanki


2 Answers

Probably you have some invalid characters in your string, like padding new lines. Try to pass NSDataBase64DecodingIgnoreUnknownCharacters option instead of 0.

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:resultString options:NSDataBase64DecodingIgnoreUnknownCharacters];
like image 158
toma Avatar answered Oct 13 '22 12:10

toma


Almost certainly your string is not valid Base64, but that it is "close enough" that base64decode.org accepts it. The most likely cause is that you've dropped a trailing =. base64decode.org is tolerant of that, and just quietly throws away what it can't decode (the last byte in that case). NSData is not tolerant of that, because it's not valid Base64.

base64decode.org is also tolerant of random non-base64 characters in the string and just throws them away. NSData is not (again, sine it's invalid).

like image 43
Rob Napier Avatar answered Oct 13 '22 14:10

Rob Napier