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.
To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.
The Base64 decoding process is very much similar to the encoding process. All you need to do is create a buffer from the Base64 encoding string by using base64 as the second parameter to Buffer. from() and then decode it to the UTF-8 string by using the toString() method.
data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
You can decode a Base64 encoded string to 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;
}
Example use of above method to get an image from the Base64 string:
-(void)imageFromBase64EncodedString{
NSString *string = @""; // replace with encocded string
NSData *imageData = [self dataFromBase64EncodedString:string];
UIImage *myImage = [UIImage imageWithData:imageData];
// do something with image
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With