Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert base64 decoded NSData to NSString

I'm trying to encode and decode base64 data. but while decoding the base64 data, it returns bunch of hex values, but i couldn't display or printout using NSlog to the original readable strings. The below code couldn't print anything, just empty.

Can anyone help ? thanks > >

NSString* msgEncoded = [[NSString alloc] initWithFormat:@"Q1NNKE1DTC9TTUEgUkNWL2FkbWluQHNldGVjcy5jb20gT1JHLyBUVkIvNDNkYzNlMzQwYWQ3Yzkp:"];  
NSData* decoded = [[NSData alloc] initWithData:[self decodeBase64WithString:msgEncoded]];
NSString* plainString = [[NSString alloc]initWithData:decoded encoding:NSUTF8StringEncoding];
NSLog(@"\n Decoded string:  %@ \n", plainString );
like image 793
hab Avatar asked Dec 09 '22 22:12

hab


2 Answers

There is a built in function in NSData

[data base64Encoding];
[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
like image 54
Nagaraj Avatar answered Jan 02 '23 23:01

Nagaraj


If you are still having issues, try out this library: https://github.com/l4u/NSData-Base64

use it like so:

#import "NSData+Base64.h"

NSData *someData  //load your data from a file, url or photo as needed
NSData *file = [NSData dataWithContentsOfFile:@"mytextfile.txt"];
NSData *photo = UIImageJPEGRepresentation(self.photo.image,1);

//encode it
NSString *base64string = [photo base64EncodedString];
NSString *base64file = [file base64EncodedString];

//decode it
NSData *back = [NSData dataFromBase64String:base64string];
like image 42
CocoaEv Avatar answered Jan 02 '23 22:01

CocoaEv