没有任何根文件夹的目录的压缩文件

问题描述 投票:0回答:1

我想将文件压缩到用 Swift 语言编写的 iOS 应用程序的文件夹中。我正在使用 ZipFoundation CocoaPod 版本 0.9.5。

let fileManager = FileManager.default

guard let sourceURL = self.folderURl else {
    print("File URL is nil.")
    return
}
var destinationURL: URL
do {
    destinationURL = try self.createExportURLZip(from: sourceURL)
    let orginfile = sourceURL.deletingLastPathComponent()

    do {
        if fileManager.fileExists(atPath: destinationURL.path) {
            try fileManager.removeItem(at: destinationURL)
        }

        let contents = try fileManager.contentsOfDirectory(at: orginfile, includingPropertiesForKeys: nil, options: [])

        // Create the archive
        guard let archive = Archive(url: destinationURL, accessMode: .create) else {
            print("Failed to create archive.")
            return
        }

        for fileURL in contents {
            let entryName = fileURL.lastPathComponent
            try archive.addEntry(with: entryName, relativeTo: orginfile, compressionMethod: .none)
        }
        print("Successfully zipped files.")
        self.zippedFilePath = destinationURL
    } catch {
        print("Error zipping contents: \(error)")
    }

} catch {
    print("Creation of ZIP archive failed with error: \(error)")
}

所以这里考虑以下情况:

  • 文件夹名称

    • 文件A.txt

    • 文件B.txt

压缩后我得到文件 Archive.zip。当我解压文件时,文件夹结构如下:

  • 存档

    • 文件A.txt

    • 文件B.txt

是否有办法对文件进行压缩,以便根文件夹 Archive 不会出现在压缩文件中,而仅出现在文件中?

这是我的后端团队要求的,就像他们想要这样的 zip 文件。

try fileManager.zipItem(at: orginfile, to: destinationURL!, shouldKeepParent: false)

我也尝试了上面的代码。它会在 unZip 上创建一个 Archive 文件夹。

我使用文件应用程序在手机本身中解压缩并检查文件。该实用程序应用程序会创建文件夹吗?

ios swift zip nsfilemanager zipfoundation
1个回答
0
投票

ZipFoundation(甚至旧版本 0.9.5)已经包含 FileManager 上的扩展,其功能就是这样做的:

public func zipItem(
         at sourceURL: URL,
    to destinationURL: URL,
     shouldKeepParent: Bool = true,
             progress: Progress? = nil) throws

顺便说一句,文档(https://developer.apple.com/documentation/foundation/filemanager/1410277-fileexists)建议不要在尝试操作之前检查文件是否存在。

所以代替:

if fileManager.fileExists(atPath: destinationURL.path) {
    try fileManager.removeItem(at: destinationURL)
}

你应该这样做:

try? fileManager.removeItem(at: destinationURL)

如果文件确实存在但由于某种原因无法删除,您在创建存档时很快就会发现。

© www.soinside.com 2019 - 2024. All rights reserved.