使用原生的Base64app
Base64是使用ASCII碼顯示二進制數據的一種流行方法。直到如今,開發者還不得不使用開源的工具來編碼解碼Base64的內容。工具
如今iOS7引入瞭如下四種新的NSData方法來操做Base64編碼的數據:編碼
// From NSData.h /* 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. */ - (id)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options; /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ - (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options; /* 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. */ - (id)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options; /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ - (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options;
這些方法能夠幫助你輕易的將NSData對象轉化爲Base64,或者將Base64轉化爲NSData object。見如下的例子:spa
NSData* sampleData = [@"Some sample data" dataUsingEncoding:NSUTF8StringEncoding]; NSString * base64String = [sampleData base64EncodedStringWithOptions:0]; NSLog(@"Base64-encoded string is %@", base64String); // prints "U29tZSBzYW1wbGUgZGF0YQ==" NSData* dataFromString = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; NSLog(@"String is %@",[NSString stringWithUTF8String:[dataFromString bytes]]); // prints "String is Some sample data"
若是你須要支持iOS6或者更早之前的系統,你能夠使用如下兩個方法:code
/* These methods first appeared in NSData.h on OS X 10.9 and iOS 7.0. They are deprecated in the same releases in favor of the methods in the <code>NSDataBase64Encoding</code> category. However, these methods have existed for several releases, so they may be used for applications targeting releases prior to OS X 10.9 and iOS 7.0. */ - (id)initWithBase64Encoding:(NSString *)base64String; - (NSString *)base64Encoding;