7

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 ?

Krish Solanki
  • 269
  • 4
  • 11

3 Answers3

10

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];
toma
  • 1,471
  • 12
  • 20
  • 1
    I was getting issue. Then I converted my data from API to string and reconverted back to data (for further decryption) using the above code. While passing 0 with the above code I was getting nil. Passing NSDataBase64DecodingIgnoreUnknownCharacters worked. – Imran Jul 02 '19 at 08:40
3

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).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • True. NSData regards non-padding base64 string as "invalid Base-64". Anyone feels needed you can refer to https://stackoverflow.com/questions/21406482/nsdata-wont-accept-valid-base64-encoded-string/21407393 for adding the paddings. – Wei WANG Dec 19 '18 at 05:16
-1

Try this! Simple solution :) Must need Foundation.framework. By default initWithBase64EncodedString method returns nil when the input is not recognized as valid Base-64. Please check your string is a valid Base-64 type or not!

    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:@"eyJuYW1lIjoidmlnbmVzaCJ9" options:0];
    NSError *dataError;
    NSDictionary* responseObject = [NSJSONSerialization JSONObjectWithData:decodedData
                                                 options:kNilOptions
                                                   error:&dataError];
   if(dataError == nil) {
        NSLog(@"Result %@",responseObject);
   }
Vignesh Kumar
  • 598
  • 4
  • 11