Converting between NSData and base64 strings Converting between NSData and base64 strings objective-c objective-c

Converting between NSData and base64 strings


Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.


Example

NSString *originalString = [NSString stringWithFormat:@"test"]; NSData *data = [NSData dataFromBase64String:originalString];  NSLog([data base64EncodedString]); 

The above will print out the original string after converting it to base64 and back to a normal unencoded string.


As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions:. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)


You don't need any custom implementation. Creating base64 from NSData is shown in other answers. There is opposite direction. From Base64 string to NSData:

 NSString *base64Encoded = @"some base64 string"; NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];