在 Swift 中如何将字节数组转换成 Base64 字符串?

7

以下是我在 Objective-C 中的示例代码:

 -(NSString *)getImageString : (unsigned char *) charValue : (unsigned long) sizeOfBytes {                   

    uint8_t commandbyte[]={ };          

    uint8_t _allBytes[(sizeOfBytes + sizeof(commandbyte))];
    memcpy(_allBytes, charValue, sizeOfBytes);

    NSMutableData *ImageData = [[NSMutableData alloc]init];
    [ImageData appendBytes:_allBytes length:sizeof(_allBytes)];

    NSString *base64String=[self base64forData:ImageData];

    return base64String;                     
}                  

- (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];
}

在这个例子中,我使用了sizeOfBytes来获取bytes,然后将它们appendNSMutableData中。以下方法用于将data转换为base64:
- (NSString*)base64forData:(NSData*)theData

在Objective C中,这非常简单,但是当我尝试使用Swift时,指针会涉及到其他概念,如UnsafeMutablePointerUnsafePointer等。

如何转换为Swift 3.0?

你们可以给我建议关于在Swift中使用指针的用法吗?


2
使用数据,请阅读https://dev59.com/81kS5IYBdhLWcg3wu4vL - Ludovic
你的实际目的是什么?你想练习如何使用Swift Data和指针,即使你知道可以使用base64EncodedString方法吗? - OOPer
2个回答

15

您可以使用以下方法将字节数组转换为base64字符串

let base64String = data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))

这个例子中,数据对象的 'type' 是什么? - metamonkey

-1

Swift 5:使用以下方式将字节数组转换为base64字符串

示例1

let plainText = "Hello world!"
print("Plain Text:", plainText)
print("Base64String:", Array(plainText.utf8).toBase64()!)

输出示例1

Plain Text: Hello world!
Base64String: SGVsbG8gd29ybGQh

例子2

let ivBase64str = "AbcnmWikMkW4c7+mHtwtfw=="
let iv = [UInt8](base64: ivBase64str)
print("BytesArray:", iv)
print("Base64String:", iv.toBase64()!)

输出示例2

BytesArray: [1, 183, 39, 153, 104, 164, 50, 69, 184, 115, 191, 166, 30, 220, 45, 127]
Base64String: AbcnmWikMkW4c7+mHtwtfw==

在第二个示例中出现了“调用中的多余参数标签'base64:'”的错误。 - metamonkey
你能否包含.toBase64()函数的定义或文档,说明它来自哪里? - micah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接