Krish Solanki
Krish Solanki

Reputation: 269

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 ?

Upvotes: 7

Views: 6286

Answers (3)

toma
toma

Reputation: 1469

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];

Upvotes: 10

Rob Napier
Rob Napier

Reputation: 299485

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

Upvotes: 3

Vignesh Kumar
Vignesh Kumar

Reputation: 598

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);
   }

Upvotes: -1

Related Questions