tags:

views:

943

answers:

2

Hello,

How to convert NSData to base64. i have NSData and want to convert into base64 how can i do this?

+1  A: 

Its not easy. As in there's no built in support for this in c or obj-c. Here's what Im doing (Which is basically having the CL do it for me):

- (NSString *)_base64Encoding:(NSString *) str
{
    NSTask *task = [[[NSTask alloc] init] autorelease];
    NSPipe *inPipe = [NSPipe pipe], *outPipe = [NSPipe pipe];
    NSFileHandle *inHandle = [inPipe fileHandleForWriting], *outHandle = [outPipe fileHandleForReading];
    NSData *outData = nil;

    [task setLaunchPath:@"/usr/bin/openssl"];
    [task setArguments:[NSArray arrayWithObjects:@"base64", @"-e", nil]];
    [task setStandardInput:inPipe];
    [task setStandardOutput:outPipe];
    [task setStandardError:outPipe];

    [task launch];

    [inHandle writeData:[str dataUsingEncoding: NSASCIIStringEncoding]];
    [inHandle closeFile];

    [task waitUntilExit];

    outData = [outHandle readDataToEndOfFile];
    if (outData)
    {
        NSString *base64 = [[[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding] autorelease];
        if (base64)
            return base64;
    }

    return nil;
}

And you use it like this:

NSString *b64str = [strToConvert _base64Encoding:strToConvert];

And this isn't my code - I found it here: http://www.cocoadev.com/index.pl?BaseSixtyFour and it works great. You could always turn this into a +() method.

Oh, and to get your NSData to an NSString for this method:

NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
Mr-sk
On the mac it isn't necessary to spawn a process - you can directly use libcrypto. On the iPhone, is /usr/bin/openssl present?
Ken
+2  A: 

Matt Gallagher wrote an article on this very topic. At the bottom he gives a link to his embeddable code for iPhone.

On the mac you can use the OpenSSL library, on the iPhone he writes his own impl.

Ken