Search code examples
ioscocoa-touchbase64nsdata

Decode Base-64 encoded PNG in an NSString


I have some NSData which is Base-64 encoded and I would like to decode it, I have seen an example that looks like this

NSData* myPNGData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];

[Base64 initialize];
NSData *data = [Base64 decode:img];
cell.image.image = [UIImage imageWithData:myPNGData];

However this gives me a load of errors, I would like to know what to do in order to get this to work. Is there some type of file I need to import into my project or do I have to include a framework?

These are the errors I get

Use of undeclared identifier 'Base64'
Use of undeclared identifier 'Base64'
Use of undeclared identifier 'cell'

I have looked everywhere and cannot figure out what is the proper thing to do.


Solution

  • NSData Base64 library files will help you.

    #import "NSData+Base64.h"
    
    //Data from your string is decoded & converted to UIImage
    UIImage *image = [UIImage imageWithData:[NSData
    dataFromBase64String:strData]];
    

    Hope it helps

    Swift 3 Version

    It's pretty much the same

    //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 Version

    //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!)