2

I am getting encoded string.string contains '=' sign at last. I am trying to decode it,using Base64 but its not decode properly.Here is my code:

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:string options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"decodedString %@", decodedString);

but, decodedString is nil.Please help me.Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3007459
  • 113
  • 1
  • 13
  • 1
    Try passing `NSDataBase64DecodingIgnoreUnknownCharacters` to the `options` parameter. – rmaddy Feb 05 '14 at 06:36
  • http://stackoverflow.com/questions/12020307/how-to-decode-convert-a-base64-string-to-nsdata – iPatel Feb 05 '14 at 06:38
  • There are online base64 encoder/decoder available.. try to verify your encoded base 64 string i.e., whether string is valid base64 encoded string or not? – Salman Zaidi Feb 05 '14 at 06:48
  • Yes,it is valid base64 encoded string. – user3007459 Feb 05 '14 at 07:01
  • 2
    Is `decodedData` already nil or not? If `decodedData` is not nil but `decodedString` is nil, then the data does not contain a valid UTF-8 string. - You should show an example Base64 string that demonstrates the problem. – Martin R Feb 05 '14 at 07:43

2 Answers2

1

The only logical explanation I can see is that the string that you are decoding is empty because that is the correct way to decode a base64 encoded.

Luis Mejías
  • 301
  • 2
  • 10
0

May be you are encoding it wrong. Try this code, its working fine and tested:

NSString *string = @"user3007459=";
NSString *base64EncodedString = [[string dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"decodedString %@", decodedString);
Ajay
  • 1,622
  • 20
  • 36