首页 > 解决方案 > 如何使用 gzip 将我从蓝牙低功耗设备获取的压缩 .gz 文件转换为 Swift 4.2 中的实际解压缩文件?

问题描述

我对 Xcode 和 iOS 非常陌生,我有一个设备,我们称之为 Brains,我使用我在 iPhone 5 上使用 Swift 4 和 Xcode 10 构建的应用程序通过蓝牙 LE 连接到它,称之为 Body。Brains 类似于 arduino 板,但不完全一样。我可以毫无问题地使用 BLE 连接并获取所有数据,直到我尝试获取一个填充了 json 字符串的压缩文件。我正在接收压缩字节,但我似乎不知道下一步该做什么。如何获取压缩文件,解压缩并读取里面的数据?

我尝试了很多使用模块的方法:GzipSwiftDataCompressionSSZipArchive

我使用过 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")

标签: swiftstringcompressionbluetooth-lowenergy

解决方案


更新后的示例数据具有正确的 gzip 标头,因此如果您将数据正确地提供给 gunzipper,则不会为您提供不正确的标头检查。


推荐阅读