【问题标题】:How to unzip a json file with password in swift?如何在swift中解压缩带有密码的json文件?
【发布时间】:2019-11-08 09:44:45
【问题描述】:

解决方案:

致收到此错误的人:

[SSZipArchive] 解压时打开文件失败。(错误域=NSPOSIXErrorDomain Code=20 "Not a directory")

使用 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 文件。

【问题讨论】:

    标签: ios json swift zip


    【解决方案1】:

    试试这个:

    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)")
        }
    }
    

    【讨论】:

    • 您好,感谢您的回复。我发现unzipFile函数的目的地应该是一个目录,这正是错误提示的含义。
    • 如果我的回答对您有帮助,请不要忘记投票。干杯!
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多