swift - 如何使用 gzip 将我从蓝牙低功耗设备获取的压缩 .gz 文件转换为 Swift 4.2 中的实际解压缩文件?
问题描述
我对 Xcode 和 iOS 非常陌生,我有一个设备,我们称之为 Brains,我使用我在 iPhone 5 上使用 Swift 4 和 Xcode 10 构建的应用程序通过蓝牙 LE 连接到它,称之为 Body。Brains 类似于 arduino 板,但不完全一样。我可以毫无问题地使用 BLE 连接并获取所有数据,直到我尝试获取一个填充了 json 字符串的压缩文件。我正在接收压缩字节,但我似乎不知道下一步该做什么。如何获取压缩文件,解压缩并读取里面的数据?
我尝试了很多使用模块的方法:GzipSwift、 DataCompression和SSZipArchive
我使用过 gunzipped()、gunzip() 和 decompress(),但它们似乎都不起作用。
我已阅读此主题:iOS :: How to decompress .gz file using GZIP Utility?它说我必须获取所有压缩字节流并将其转换为 NSData 然后解压缩,问题是他正在使用objective-c,我似乎无法翻译成swift 4。
我[UInt8]
在这个函数中从数组中的蓝牙 LE 特征中获取字节:
func received_logs(data: [UInt8]) {
let data_array_example = [31, 139, 8, 8, 16, 225, 156, 92, 2, 255, 68, 97, 116, 97, 0, 181, 157, 107, 110, 220, 56, 16, 6, 175, 226, 3, 248, 71, 63, 73, 234, 44, 193, 222, 255, 26, 171, 30, 35, 192, 90, 20, 18, 121, 182, 11, 112, 16, 35, 48, 10, 31, 154, 197, 22, 135, 34, 227, 95, 191, 76, 244, 16, 183, 248, 252, 48, 137, 229, 38, 242, 249, 161, 231, 87, 156, 127, 207, 113, 126, 227, 159, 31, 231, 183, 110, 223, 255, 200, 239, 47, 203, 252, 253, 173, 255, 231, 159, 235, 235, 108, 105, 110, 101, 48, 47, 50, 48]
for data_byte in stride(from: 0, to: data_array_example.count, by: 1) {
let byte = String(data_array_example[data_byte])
sourceString = sourceString + byte //getting all the bytes and converting to string to store in a variable
}
/******************************************************************/
let text = sourceBuffer
do {
try text.write(to: path!, atomically: false, encoding: String.Encoding.utf8)
}
catch {
print("Failed writing")
} //dump the var into a txt file
/**********UPDATED**********/
var file_array : [UInt8] = []
let byte2 = NSData(data: data_array_example.data)
let asc_array = Data(bytes: byte2.data)
let decompressedData: Data
do {
try decompressedData = asc.gunzipped()
print("Decom: ", String(data: decompressedData, encoding: .utf8))
}
catch {
print(error) //Gives me the "unknown compression method error"
}
}
我希望看到未压缩文件的内容,但我只得到:
GzipError(kind: Gzip.GzipError.Kind.data, message: "incorrect header check")
也许我只是让它变得比它需要的更复杂。任何帮助将不胜感激!
非常感谢 :)
更新: 我创建了一个 .gz 文件并使用了 gunzipped() 和 gunzip() 函数,它们都有效。
更新:
试图直接将数据转换为 NSData 然后 gunzip() 但现在得到错误:
GzipError(kind: Gzip.GzipError.Kind.data, message: "unknown compression method")
解决方案
更新后的示例数据具有正确的 gzip 标头,因此如果您将数据正确地提供给 gunzipper,则不会为您提供不正确的标头检查。
推荐阅读
- python - super().__init__(model, year, position) TypeError: __init__() missing 1 required positional argument: 'position'
- docker - 将默认 0.0.0.0 从 docker 更改为特定
- rust - 创建一个临时的,在仍在使用时被释放
- visual-studio-code - 如何禁用 vscode 的内置建议?
- powershell - Powershell 长度不会显示在 Get-ChildItem 的输出中
- java - 尝试将不干净记录的表验证到具有干净数据的新表时出现 QuerySyntaxException。需要映射实体吗?
- python - 使用 PyBluez 和 PyOBEX 通过蓝牙发送文件
- css - 为什么我不能使用 sass 变量来定义 css 变量的值
- java - Eclipse条件断点和全局变量?
- c++ - 如何使用 C++ 在文件中间添加阿拉伯字符?