iOS7 base64编解码

文档

@interface NSData (NSDataBase64Encoding)

/* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64 encoded NSString from the receiver's contents using the given options.
*/
- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options.
*/
- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

@end

使用

NSString *str = @"我是字符串";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

NSData *base64Data = [data base64EncodedDataWithOptions:0];
NSString *base64Str = [data base64EncodedStringWithOptions:0];

NSLog(@"%@", base64Str);

NSData *dataDecoded1 = [[NSData alloc] initWithBase64EncodedData:base64Data options:0];
NSData *dataDecoded2 = [[NSData alloc] initWithBase64EncodedString:base64Str options:0];
NSString *strDecoded1 = [[NSString alloc] initWithData:dataDecoded1 encoding:NSUTF8StringEncoding];
NSString *strDecoded2 = [[NSString alloc] initWithData:dataDecoded2 encoding:NSUTF8StringEncoding];

NSLog(@"strDecoded1: %@", strDecoded1);
NSLog(@"strDecoded2: %@", strDecoded2);

参考

  • 使用Base64编解码NSData和NSString对象

你可能感兴趣的:(iOS7 base64编解码)