我正在尝试将字节数组转换为Swift中的String。我有一个关于Android解码如何工作的例子。但是,由于我是Swift的新手,我在翻译时遇到了问题。 以下是Android代码段:
private String packageHead = null;
private byte numberPackages = 0;
private ArrayList<byte[]> usageData = null;
if (BluetoothLEService.ACTION_DATA_AVAILABLE.equals(action)) {
final byte[] txValue = intent.getByteArrayExtra(BluetoothLEService.EXTRA_DATA);
runOnUiThread(new Runnable() {
public void run() {
if(packageHead == null){
packageHead = txValue[0] + "";
numberPackages = txValue[1];
usageData = new ArrayList<byte[]>(numberPackages);
}
if(packageHead.equals(txValue[0] + "")){
usageData.add(txValue[2], getUsageData(txValue));
}
boolean transmissionDone = (usageData.size() == numberPackages);
if(transmissionDone){
packageHead = null;
processBluetoothPackages(usageData);
usageData = null;
}
}
});
}
private byte[] getUsageData(byte[] txValue) {
byte[] ret = new byte[txValue.length - 3];
for(int i = 0; i < ret.length; ++i){
ret[i] = txValue[i+3];
}
return ret;
}
private void processBluetoothPackages(List<byte[]> usageDataParam) {
int size = 0;
for (byte[] arr : usageDataParam) {
size += arr.length;
}
byte[] usageDataArr = new byte[size];
int index = 0;
for (byte[] arr : usageDataParam) {
for(byte b : arr){
usageDataArr[index] = b;
++index;
}
}
String text = new String(usageDataArr, StandardCharsets.UTF_8);
}
};
要解码的字节数组是[170,2,0,104,116,116,112,58,47,47,119,119,119,46,97,100,101,115,115,111 ]。 我在Swift中的问题是在字节数组中似乎有许多包我需要解码。我无法像在Android中那样与他们联系。 任何帮助表示赞赏。谢谢!
更新
我正在尝试使用Swift技术。但是,我只得到“零”。我尝试过的所有提示都会产生相同的结果。
let data = characteristic.value;
let values = [UInt8](data!);
var dataString = String(data: data!, encoding: String.Encoding.utf8);
print("Raw data: \(String(describing: values))");
print("String data: \(String(describing: values))");
结果是: 原始数据:[170,2,0,104,116,116,112,58,47,47,119,119,119,46,97,100,101,115,115,111] 字符串数据:nil