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?