首页 > 解决方案 > 如何在swift中解压缩带有密码的json文件?

问题描述

解决方案:

对于遇到此错误的人:

[SSZipArchive] 无法在解压缩时打开文件。(错误域 = NSPOSIXErrorDomain 代码 = 20 “不是目录”)

使用 unzipFile 函数时,请确保目标是一个目录。

SSZipArchive.unzipFile(atPath: String, toDestination: String, overwrite: Bool, password: String?)

问题:

如何在 Swift 中解压带密码的 json 文件?我使用第三方SDK并下载了一个文件,文件类型为Data.

该文件被宣布为 zip 文件,需要解压为json带有密码的文件。

我将文件保存到FileManager.documentDirectory并用.zip扩展名命名。然后我尝试用 解压缩文件ZipArchive,但出现以下错误:

[SSZipArchive] Failed to open file on unzipping.(Error Domain=NSPOSIXErrorDomain Code=20 "Not a directory")

我还保存了带有.json扩展名的文件,然后将其解压缩,但出现与上述相同的错误。

我在容器中下载了保存的文件并打开它,结果如下所示:

(1) 到一个.zip文件:我无法打开它。

Can't decompressed xxx.json.zip to Documents.
(error -2: No similar file or directory)

(2)到.json文件:我得到了一些乱码,比如

∫ôFk;|T|D˚®è•Éjê‹¡Ò;X≈∞)˘–7ÑØZl≥MÇz-n·ù!ê}˜fflêÔæv\£F>RBZ1Myfª—Q˘∏àúˇá≥˙Ïèãd”

这里显示了我的代码。

func saveZipFile(filename: String, file: Data) {
    let documentDirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = documentDirURL.appendingPathComponent("\(filename).zip")
    print("File Path: \(fileURL.path)")

    do {
        try file.write(to: fileURL, options: .atomic)

        try SSZipArchive.unzipFile(atPath: fileURL.path, toDestination: fileURL.path, overwrite: true, password: finalKey)
    } catch let err {
        print("Error: \(err.localizedDescription)")
    }
}

如果解压缩正确,该文件应该是人类可读的 json 文件。

标签: iosjsonswiftzip

解决方案


尝试这个:

func saveZipFile(filename: String, file: Data) {

    let documentDirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = documentDirURL.appendingPathComponent("\(filename).zip")
    let destination = documentDirURL.path + "/MyZipFiles"
    print("File Path: \(fileURL.path)")

    do {
        try file.write(to: fileURL, options: .atomic)

        try SSZipArchive.unzipFile(atPath: fileURL.path, toDestination: destination, overwrite: true, password: finalKey)
    } catch let err {
        print("Error: \(err.localizedDescription)")
    }
}

推荐阅读