Base64 encoding in Cocoa

16 02 2008

While there are implementations written in Objective-C or making use of openssl(CocoaDev: BaseSixtyFour), on Leopard, you can also use Apache Portable Runtime functions.

1. Import header files nessesary to base64 encoding.

#import <apr-1/apr.h>
#import <apr-1/apr_base64.h>

2. Add linker flags.
Open “build settings” dialog page, add following flags to OTHER_LDFLAGS item(screenshot is taken in Japanese environment).

-laprutil-1 -lapr-1

linker_flag1

3. apr functions cannot recognize NSString nor CFStringRef, make wrapper around.

static NSString* encode_to_base64(NSString* source_str)
{
    char *source_cstr = (char*)[source_str UTF8String];

    int source_length = strlen(source_cstr);
    int result_length = apr_base64_encode_len(source_length);
    char *encoded_buf = malloc(result_length);
    apr_base64_encode(encoded_buf, source_cstr, source_length);

    NSString *resultString = [NSString stringWithCString:encoded_buf];

    free(encoded_buf);
    return resultString;
}

4. Use above routine in your program.

NSString *testString = @"Test";
NSString *base64String = encode_to_base64(testString);

Actions

Information

Leave a comment