Search code examples
objective-cuiimagebase64nsdata

iOS decodeBase64ToImage returning nil on valid base 64 encoded image


I am trying to turn a base 64 canvas string into a UIImage but I always get nil.

Here is strEncodeData as a gist

https://gist.github.com/blasto333/5f15ab56dee0dbf790d90e9064160ea7#file-base64-receipt-image

Code

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

data is ALWAYS nil


Solution

  • The base64 string is not a normal base64 encoded string. It's a special data: schemed URL. It begins with data:image/png;base64, which is then followed by the encoded data.

    You need:

    - (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
        NSURL *url = [NSURL URLWithString: strEncodeData];
        NSData *imageData = [NSData dataWithContentsOfURL: url];
        UIImage *image = [UIImage imageWithData: imageData];
    
        return image;
    }