ios - 在 NSString 中解码 Base-64 编码的 PNG

标签 ios cocoa-touch base64 nsdata

我有一些 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
}

关于ios - 在 NSString 中解码 Base-64 编码的 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16704915/

相关文章:

iphone - 将文件添加到特定构建配置的目标

c++ - 使用 Crypto++ Base64 编码器时避免换行

javascript - Base64 编码图像主机 url 或服务器文件路径

ios - iOS9.1 的UITouchType

ios - 水平 Collection View 内容宽度和间距

iphone - 为什么设置图层边界矩形的anchorPoint 行为如此奇怪?

android - 如何在 Android 中使用 HTTP POST 将图像作为 JSON 中的 base64 字符串发送?

ios - 使用 Swift 和 Xcode 6.4 进行调试?

ios - 如何从 url 获取 objectID?

ios - 我的 NSString 数据没有传输到 View Controller