Zip files of a Directory without any root folder

109 Views Asked by At

I want to zip files inside a folder in my iOS application written in the Swift language. I am using ZipFoundation CocoaPod of version 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)")
}

So here consider the below case:

  • FolderName

    • FileA.txt

    • FileB.txt

After zipping I get the file Archive.zip. When I unzip the file the folder structure is as below:

  • Archive

    • FileA.txt

    • FileB.txt

Is there anyway to zip files so that the root folder Archive won't be in zipped file, just the files only?

This is requested by my backend team, like they want the zip file like that.

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

I tried the above code too. It creates an Archive folder on unZip.

I used Files app to unzip in mobile itself and checked the files. Do the utility app creates a folder?

1

There are 1 best solutions below

0
Jack Goossen On

ZipFoundation (even the old version 0.9.5) already contains an extension on FileManager with a function that does just that:

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

As a side note, the documentation (https://developer.apple.com/documentation/foundation/filemanager/1410277-fileexists) recommends against checking for file existence before attempting an operation.

So instead of:

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

You should just do:

try? fileManager.removeItem(at: destinationURL)

In case the file does exist but cannot be removed for some reason, you'll find out soon enough when creating the archive.