Update: This article is now happily obsolete. Apple have published their existing Base64 encoding methods on NSData for use back to OS X 10.6 and iOS 4.
Here's a handy technical tidbit, something that Dan discovered when trying to simplify some of the code we built back when we were getting Sandvox ready for the Mac App Store.
We needed an implementation of Base64 encoding and decoding. Foundation still doesn't have a public API after all these years (you should of course file a radar, duping Cédric Luthi's). We had been using an implementation in one of the libraries that we were trying to avoid linking to. So Dan did some grepping through various libraries, and found that SASL has an implementation of Base64!
So we just wrapped some simple implementations around these C-based functions:
Of course, your project will need to link to libsasl2.dylib. Note that this probably isn't doable on iOS.
Since publicising this on Twitter, a variety of people have mentioned their own preferences. So here's a quick list:
- The first post I remember reading on the subject: Matt Gallagher's self-contained code
- Dave Dribin created dedicated encoder and decoder classes; here are the tests
- Simon Thulbourn went to the trouble of porting PHP's methods
- Peter Hosey points out that OS X 10.7 Lion provides this functionality via the SecTransform APIs
- Daniel Jalkut is using Dave Winer's old code
- Cédric Luthi is coercing property list serialisation into doing it for him
- James Montgomerie has a similar solution to ours, using the BIND-9 DNS resolution library
- And of course as mentioned above, Apple finally publish proper Cocoa API these days!