Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...