Base64 encode and decode an NSString in Cocoa


Matt Gallagher has a NSData+Base64 catagory for extending an NSData object. I wanted to be able to encode and decode an NSString both ways.

 

- (NSString *)base64Encode:(NSString *)plainText
{
  NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
  NSString *base64String = [plainTextData base64EncodedString];
  return base64String;
}
 
- (NSString *)base64Decode:(NSString *)base64String
{
  NSData *plainTextData = [NSData dataFromBase64String:base64String];
  NSString *plainText = [[NSString alloc] initWithData:plainTextData encoding:NSUTF8StringEncoding];
  return plainText;
}
© 2011 Adam Gerson.