π A framework for zipping and unzipping files in Swift.
Simple and quick to use. Built on top of Minizip 1.2.
Use the SPM string to easily include the dependendency in your Package.swift
file.
.package(url: "https://github.com/vapor-community/Zip.git", from: "2.2.0")
and add it to your target's dependencies:
.product(name: "Zip", package: "zip")
Zip supports all platforms supported by Swift 5.9 and later.
To use Zip on Windows, you need to pass an available build of zlib
to the build via extended flags. For example:
swift build -Xcc -I'C:/pathTo/zlib/include' -Xlinker -L'C:/pathTo/zlib/lib'
The easiest way to use Zip is through quick functions. Both take local file paths as URL
s, throw if an error is encountered and return an URL
to the destination if successful.
import Zip
do {
let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
let unzipDirectory = try Zip.quickUnzipFile(filePath)
let zipFilePath = try Zip.quickZipFiles([filePath], fileName: "archive")
} catch {
print("Something went wrong")
}
For more advanced usage, Zip has functions that let you set custom destination paths, work with password protected zips and use a progress handling closure. These functions throw if there is an error, but don't return.
import Zip
do {
let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
try Zip.unzipFile(filePath, destination: documentsDirectory, password: "password") { progress in
print(progress)
}
let zipFilePath = documentsFolder.appendingPathComponent("archive.zip")
try Zip.zipFiles([filePath], zipFilePath: zipFilePath, password: "password") { progress in
print(progress)
}
} catch {
print("Something went wrong")
}
Zip provides a way to archive data saved in memory. This is useful when you want to create a zip archive without having the source files saved to disk.
import Zip
do {
let archiveFile = ArchiveFile(filename: "file.txt", data: "Hello, World!".data(using: .utf8)!)
let zipFilePath = FileManager.default.temporaryDirectory.appendingPathComponent("archive.zip")
try Zip.zipData(archiveFiles: [archiveFile], zipFilePath: zipFilePath)
} catch {
print("Something went wrong")
}
Zip supports .zip
and .cbz
files out of the box. To support additional zip-derivative file extensions:
Zip.addCustomFileExtension("file-extension-here")