Converting NSData to base64

Viewed 60700

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

7 Answers

EDIT

As of OS X 10.9 / iOS 7, this is built into the frameworks.

See -[NSData base64EncodedDataWithOptions:]


Prior to iOS7/OS X 10.9:

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.

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