vapor-community / Zip

📂 A framework for zipping and unzipping files in Swift
https://swiftpackageindex.com/vapor-community/Zip
MIT License
3 stars 1 forks source link
minizip swift swift-library swift-linux swift-package swift-package-manager unzip unzipping-files zip ziparchive
avatar Documentation Team Chat MIT License Continuous Integration Swift 5.8+


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")

Usage

Quick Functions

The easiest way to use Zip is through quick functions. Both take local file paths as URLs, 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")
}

Advanced Zip

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, overwrite: true, 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")
}

Archive Data saved in memory

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")
}

Custom File Extensions

Zip supports .zip and .cbz files out of the box. To support additional zip-derivative file extensions:

Zip.addCustomFileExtension("file-extension-here")