我有一些NSData
Base-64编码,我想解码它,我看到一个看起来像这样的例子
NSData* myPNGData = [xmlString dataUsingEncoding:NSUTF8StringEncoding]; [Base64 initialize]; NSData *data = [Base64 decode:img]; cell.image.image = [UIImage imageWithData:myPNGData];
然而,这给了我一大堆错误,我想知道该怎么做才能使这个工作.我需要将某些类型的文件导入到我的项目中,还是必须包含一个框架?
这些是我得到的错误
Use of undeclared identifier 'Base64' Use of undeclared identifier 'Base64' Use of undeclared identifier 'cell'
我到处寻找,无法弄清楚做什么是正确的.
您可以将Base64编码的字符串解码为NSData
:
-(NSData *)dataFromBase64EncodedString:(NSString *)string{ if (string.length > 0) { //the iPhone has base 64 decoding built in but not obviously. The trick is to //create a data url that's base 64 encoded and ask an NSData to load it. NSString *data64URLString = [NSString stringWithFormat:@"data:;base64,%@", string]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]]; return data; } return nil; }
使用上述方法从Base64字符串中获取图像的示例:
-(void)imageFromBase64EncodedString{ NSString *string = @""; // replace with encocded string NSData *imageData = [self dataFromBase64EncodedString:string]; UIImage *myImage = [UIImage imageWithData:imageData]; // do something with image }
NSData Base64库文件将为您提供帮助.
#import "NSData+Base64.h" //Data from your string is decoded & converted to UIImage UIImage *image = [UIImage imageWithData:[NSData dataFromBase64String:strData]];
希望能帮助到你
Swift 3版
它几乎是一样的
//Create your NSData object let data = NSData(base64Encoded: "yourStringData", options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) //And then just create a new image based on the data object let image = UIImage(data: data as! Data)
Swift 2.3版本
//Create your NSData object let data = NSData(base64EncodedString: "yourStringData", options: .IgnoreUnknownCharacters) //And then just create a new image based on the data object let image = UIImage(data: data!)
//retrieve your string NSString *string64 = //... some string base 64 encoded //convert your string to data NSData *data = [[NSData alloc] initWithBase64EncodedString:string64 options:NSDataBase64DecodingIgnoreUnknownCharacters]; //initiate image from data UIImage *captcha_image = [[UIImage alloc] initWithData:data];