我需要一种方法将UInt8数组转换为Base64 String。我在Java中有一个例子,但我在将Java代码转换为Swift时遇到了麻烦。这是java代码:
private static String getBase64(byte[] buffer)
{
final char[] map = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buffer.length; i++)
{
byte b0 = buffer[i++], b1 = 0, b2 = 0;
int bytes = 3;
if (i < buffer.length)
{
b1 = buffer[i++];
if (i < buffer.length)
{
b2 = buffer[i];
}
else
{
bytes = 2;
}
}
else
{
bytes = 1;
}
int total = (b0 << 16) | (b1 << 8) | b2;
switch (bytes)
{
case 3:
sb.append(map[(total >> 18) & 0x3f]);
sb.append(map[(total >> 12) & 0x3f]);
sb.append(map[(total >> 6) & 0x3f]);
sb.append(map[total & 0x3f]);
break;
case 2:
sb.append(map[(total >> 18) & 0x3f]);
sb.append(map[(total >> 12) & 0x3f]);
sb.append(map[(total >> 6) & 0x3f]);
sb.append('=');
break;
case 1:
sb.append(map[(total >> 18) & 0x3f]);
sb.append(map[(total >> 12) & 0x3f]);
sb.append('=');
sb.append('=');
break;
}
}
return sb.toString();
}
现在这是我到目前为止在Swift中所遇到的,我遇到了StringBuffer和java示例中的情况:
private static func getBase64(buffer : [UInt8]) {
let map : Array<Character> = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "+", "/"
]
// String Buffer?
for var i = 0; i < buffer.count; i++ {
var b0 : UInt8 = buffer[i++]
var b1 : UInt8 = 0
var b2 : UInt8 = 0
var bytes : Int = 3
if i < buffer.count {
b1 = buffer[i++]
if i < buffer.count {
b2 = buffer[i]
} else {
bytes = 2
}
} else {
bytes = 1
}
let total : Int = Int((b0 << 16) | (b1 << 8) | b2)
switch bytes
{
case 3:
// not sure
break
case 2:
// not sure
break
case 1:
// not sure
break
}
}
}
Swift如何实现StringBuffer,如何构建我的案例,就像Java代码在swift中一样?任何帮助表示赞赏。
答案 0 :(得分:2)
假设你真正想要的是一种将字符串转换为Base64的方法,这是一种简单的方法:
import Foundation
extension String {
func UTF8toBase64() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
return data?.base64EncodedStringWithOptions([]) ?? ""
}
func Base64toUTF8() -> String {
let data = NSData.init(base64EncodedString: self, options: []) ?? NSData()
return String(data: data, encoding: NSUTF8StringEncoding) ?? ""
}
}
let string = "Test"
let string64 = string.UTF8toBase64() // => "VGVzdA=="
let string2 = string64.Base64toUTF8() // => "Test
当然,这一直假设UTF-8,你可能想要允许其他编码。