How do I do base64 encoding on iOS?

At the time this question was originally posted, people were understandably directing you to third-party base 64 libraries because of the lack of any native routines. But iOS 7 introduced base 64 encoding routines (which actually simply just exposes private methods iOS had going back to iOS 4).

So, you can use the NSData method base64EncodedStringWithOptions: to create a base-64 string from a NSData.

NSString *string = [data base64EncodedStringWithOptions:kNilOptions];

And you can use initWithBase64EncodedString:options: to convert a base-64 string back to a NSData:

NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions]; 

Or, in Swift:

let string = data.base64EncodedString()


let data = Data(base64Encoded: string)

Leave a Comment