How to encode NSData as base64? (iPhone/iPad)

后端 未结 2 845
孤街浪徒
孤街浪徒 2021-01-07 13:00

I\'m trying to add a UIImage to an HTML email, however I\'m having an issue. I have looked around at lots of other posts and they all state that I need to conve

相关标签:
2条回答
  • 2021-01-07 13:36

    The method you are trying to use doesn come with default framework. You can add the NSData category to your project.

    0 讨论(0)
  • 2021-01-07 13:57
    + (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
    
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
    
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
    }
    
    0 讨论(0)
提交回复
热议问题