Zip files of a Directory without any root folder – iOS Swift


I want to Zip files inside a folder in my iOS Application written in 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

After zipping , i get the file Archive.zip. When i unzip the file the folder structure is as below

Is there anyway to zip files so that the root folder Archive wont 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.

Thanks for help in advance

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img