将base64解码的NSData转换为NSString

时间:2012-08-06 16:21:50

标签: objective-c ios nsstring nsdata

我正在尝试编码和解码base64数据。但是在解码base64数据时,它会返回一组十六进制值,但我无法使用NSlog显示或打​​印输出到原始可读字符串。下面的代码无法打印任何内容,只是空白。

有人可以帮忙吗?谢谢 > >

NSString* msgEncoded = [[NSString alloc] initWithFormat:@"Q1NNKE1DTC9TTUEgUkNWL2FkbWluQHNldGVjcy5jb20gT1JHLyBUVkIvNDNkYzNlMzQwYWQ3Yzkp:"];  
NSData* decoded = [[NSData alloc] initWithData:[self decodeBase64WithString:msgEncoded]];
NSString* plainString = [[NSString alloc]initWithData:decoded encoding:NSUTF8StringEncoding];
NSLog(@"\n Decoded string:  %@ \n", plainString );

3 个答案:

答案 0 :(得分:7)

NSData中有内置函数

[data base64Encoding];
[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];

答案 1 :(得分:5)

如果您仍然遇到问题,请试用此库:https://github.com/l4u/NSData-Base64

像这样使用它:

#import "NSData+Base64.h"

NSData *someData  //load your data from a file, url or photo as needed
NSData *file = [NSData dataWithContentsOfFile:@"mytextfile.txt"];
NSData *photo = UIImageJPEGRepresentation(self.photo.image,1);

//encode it
NSString *base64string = [photo base64EncodedString];
NSString *base64file = [file base64EncodedString];

//decode it
NSData *back = [NSData dataFromBase64String:base64string];

答案 2 :(得分:1)

尝试Google的GTMStringEncoding课程。你也需要GTMDefines.h

GTMStringEncoding *coder = [GTMStringEncoding rfc4648Base64StringEncoding];
NSString *encodedBase64 = [coder encodeString:@"Mary had a little lamb"];

// will contain the original text
NSString *decodedText = [coder decodeString:encodedBase64];

要将NSData*编码为NSString*并返回NSData*,请使用encode: + decode:方法代替encodeString: + {{1 }}

作为奖励,您可以获得许多其他有用的编码,例如Base64的url-safe variant