Swift implements file compression and decompression sample code

  • 2020-05-19 06:02:29
  • OfStack

Sometimes files need to be downloaded and decompressed in the project. In the project, ZipArchive is selected, which is relatively simple to use in practice. You can directly call the decompression and compression methods.

The compression


@IBAction func zipAction(_ sender: UIButton) {
  let imageDataPath = Bundle.main.bundleURL.appendingPathComponent("FlyElephant").path

  zipPath = tempZipPath()

  let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: imageDataPath)
  if success {
   print(" Compression success ---\(zipPath!)")
  }
 }

# decompression


@IBAction func unZipAction(_ sender: UIButton) {
  guard let zipPath = self.zipPath else {
   return
  }

  guard let unzipPath = tempUnzipPath() else {
   return
  }

  let success = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath)
  if !success {
   return
  }
  print(" Unpack the success ---\(unzipPath)")
  var items: [String]
  do {
   items = try FileManager.default.contentsOfDirectory(atPath: unzipPath)
  } catch {
   return
  }

  for (index, item) in items.enumerated() {
   print("\(index)-- The file name ---\(item)")
  }
 }

Compression and decompression paths:


func tempZipPath() -> String {
  var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
  path += "/\(UUID().uuidString).zip"
  return path
 }

 func tempUnzipPath() -> String? {
  var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
  path += "/\(UUID().uuidString)"
  let url = URL(fileURLWithPath: path)

  do {
   try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
  } catch {
   return nil
  }


  return url.path
 }


Related articles: