iOS :: 如何使用 GZIP Utility 解压缩 .gz 文件?

iOS :: How to decompress .gz file using GZIP Utility?

我将我的sqlite 数据库以.gz 格式保存在S3 服务器中。 当我的 iOS 应用程序启动时,我想下载 .gz 文件中的数据库并将其解压缩到文档目录中。

下载部分正常,但解压失败

我试过 ZipArchive,但它不能解压缩 .gz 文件。它能够解压缩 ZIP 文件。下面是代码,我试过了。

 ZipArchive *za = [[ZipArchive alloc] init];

if ([za UnzipOpenFile:filePath]) {
    BOOL ret = [za UnzipFileTo:destPath overWrite:YES];
    [za UnzipCloseFile];
    [za release];

    if (ret == YES) {
        [self stopSpinner];

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[appDelegate encTitle] message:@"Update successful.\nPlease restart the application for changes to take effect." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
            } else {
                //Didn't work
            }
        }

我在 iOS 中找到了解压的 GZIP,但不知道如何使用它。如果有人有想法,请与我分享。 Link 用于 GZIP :: https://github.com/nicklockwood/GZIP

如果有人知道任何其他用于.gz解压的库......也欢迎他们。

您在使用 GZIP 库时遇到的具体困难是什么?

您需要做的就是在 NSData 实例上调用 gunzippedData,它将 return 一个包含解压缩数据的新 NSData 对象。

更新

GZIP 库不能处理文件,但它可以直接处理 NSData 的实例。这意味着您必须 construct an NSData object from your compressed .gz file manually, uncompress it, and write the uncompressed data 到文档目录...

// assuming filePath is a valid local path to the .gz file
NSError *error = nil;

// Create an NSData instance from the file
NSData *compressedData = [NSData dataWithContentsOfFile:filePath options:0 error:&error];
if (!compressedData) {
    NSLog(@"Reading file failed: %@", error);
}
else {
    // Attempt to uncompress it
    NSData *uncompressedData = [compressedData gunzippedData];
    if (!uncompressedData) {
        NSLog(@"Decompression failed");
    }
    else {
        // Write the uncompressed data to disk
        // You will need to set pathToSQLiteFile to the desired location of the SQLite database
        [uncompressedData writeToFile:pathToSQLiteFile atomically:YES];
    }
}

我围绕 Apple 自己的压缩库 DataCompression 维护了一个轻量级 Swift 3+ 包装库。除此之外,它还支持 GZIP 格式。

解压缩 .gz 文本文件并打印内容如下所示:

import DataCompression

let compressedData = try? Data(contentsOf: URL(fileURLWithPath: "/path/to/your/file.txt.gz"))

if let uncompressedData = compressedData?.gunzip() {
    print(String(data: uncompressedData, encoding: .utf8) ?? "Can't decode UTF-8")
}

您可以参考 README 以获得界面和其他压缩格式的完整概述。