Converting NSData to base64

Solution 1:

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.

Solution 2:

//from: http://cocoadev.com/BaseSixtyFour
+ (NSString*)base64forData:(NSData*)theData {

    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

  static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
  uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
  for (i=0; i < length; i += 3) {
    NSInteger value = 0;
        NSInteger j;
    for (j = i; j < (i + 3); j++) {
      value <<= 8;

      if (j < length) {
        value |= (0xFF & input[j]);
      }
    }

    NSInteger theIndex = (i / 3) * 4;
    output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
    output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
    output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
    output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
  }

  return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}

Solution 3:

As an update, the iOS7 SDK has a category on NSData (NSDataBase64Encoding) with methods

-[NSData base64EncodedStringWithOptions:]
-[NSData initWithBase64EncodedString:options:]
-[NSData initWithBase64EncodedData:options:]
-[NSData base64EncodedDataWithOptions:]

Should avoid having to roll your own category method

Solution 4:

Super easy drop-in Google library code here.

Just use +rfc4648Base64StringEncoding to get an instance, then use the encode/decode functions.

It's a beautiful thing. (Don't forget to grab the header file and the GTMDefines.h header from the root, though.)

Solution 5:

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