如何压缩文件而不在 zip 目录中创建目录?

Abh*_*bhi 2 zip ios swift zipfoundation

我正在尝试在目标路径中压缩文件。一切正常。我的文件被压缩到目标 URL。但问题是当我解压缩时,我的文件在目录中。我不希望我的文件在目录中。当我解压缩时,我想查看我的文件。

这是我的代码:

func zipData() {
    let  path=NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true).first!
    let fileManager = FileManager()

    var sourceURL = URL(fileURLWithPath: path)
    sourceURL.appendPathComponent("/cropsapdb_up_\(useridsaved)")

    var destinationURL = URL(fileURLWithPath: path)
    destinationURL.appendPathComponent("/cropsapdb_up_\(useridsaved).zip")
    do {
        let fm = FileManager.default
        let items = try fm.contentsOfDirectory(atPath: sourceURL.path)
        guard let archive = Archive(url: destinationURL, accessMode: .create) else  {
            print("returning")
            return
        }

        for item in items {
            sourceURL = sourceURL.appendingPathComponent("/\(item)")

            try archive.addEntry(with: sourceURL.lastPathComponent, relativeTo: sourceURL.deletingLastPathComponent())
            guard let archive = Archive(url: destinationURL, accessMode: .update) else  {
                print("returning")
                return
            }

            sourceURL.deleteLastPathComponent()
        }
    } catch {
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*ing 7

我是您正在使用的库ZIP Foundation的作者。

如果我正确理解您的代码,您希望递归地将目录的内容添加到 ZIP 存档中。
为此,您可以使用在 ZIP Foundation 中zipItem作为扩展实现的便捷方法FileManager
默认情况下,它的行为类似于 macOS 上的存档实用程序,并包含sourceURL存档根目录的最后一个目录名称。要改变这种行为(正如 Leo Dabus 在评论中指出的那样),您可以传递可选shouldKeepParent: false参数:

func zipData() {
    let useridsaved = 1
    
    let fileManager = FileManager.default
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true).first!
    var sourceURL = URL(fileURLWithPath: path)
    sourceURL.appendPathComponent("cropsapdb_up_\(useridsaved)")
    var destinationURL = URL(fileURLWithPath: path)
    destinationURL.appendPathComponent("cropsapdb_up_\(useridsaved).zip")
    do {
        try fileManager.zipItem(at: sourceURL, to: destinationURL, shouldKeepParent: false)
    } catch {
        print(error)
    }
}
Run Code Online (Sandbox Code Playgroud)

(我添加了一个虚构的let useridsaved = 1局部变量以使您的示例可编译)

要验证存档确实不包含根目录,您可以使用zipinfomacOS 附带的命令行实用程序。
也有可能是您服务器上的邮政编码在解压您的档案时隐式地创建了一个目录。