iOS之后,NSData新增一个类别用于编解码NSData。
@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:
// 字符串转Data
NSString *str = @"encode string";
// 字符串转成Data
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];// 13 bytes
// 编码Data
NSData *encodeData = [data base64EncodedDataWithOptions:0];// 20 bytes
// 解码Data
NSData *decodeData = [[NSData alloc] initWithBase64EncodedData:encodeData options:0];// 13 bytes
// Data转字符串
NSString *decodeStr = [[NSString alloc] initWithData:decodeData encoding:NSUTF8StringEncoding];
NSLog(@"%@",decodeStr);// encode string
以上的方法是通用方法,不过考虑到开发者使用NSData编解码NSString比较多,苹果提供了更直接的API编解码NSString:
// 字符串转Data并且编码
NSData *data = [[NSData alloc] initWithBase64EncodedString:@"encode string" options:0];
// Data解码并且转字符串
NSString *decodeStr = [data base64EncodedStringWithOptions:0];
NSLog(@"%@",decodeStr);// encode string
编解码UIImage:
UIImage *img = [UIImage imageNamed:@"image.jpg"];
// 图片转Data
NSData *data = UIImageJPEGRepresentation(img, 0.7);
// 编码Data
NSData *encodeData = [data base64EncodedDataWithOptions:0];
// 解码Data
NSData *decodeData = [[NSData alloc] initWithBase64EncodedData:encodeData options:0];
// Data转图片
UIImage *decodeImg = [UIImage imageWithData:decodeData];
总结:
编解码是只有NSData才能穿上脱下的隐身斗篷。