swift 解压缩 Swift实现文件压缩和解压代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

swift 解压缩 Swift实现文件压缩和解压代码实例

FlyElephant   2021-03-24 我要评论
想了解Swift实现文件压缩和解压代码实例的相关内容吗,FlyElephant在本文为您仔细讲解swift 解压缩的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:swift,解压缩,swift3,解压文件,下面大家一起来学习吧。

项目中有时候需要文件下载解压,项目中选择了ZipArchive,实际使用也比较简单,直接调用解压和压缩方法即可.

压缩

@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("压缩成功---\(zipPath!)")
  }
 }

#解压

@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("解压成功---\(unzipPath)")
  var items: [String]
  do {
   items = try FileManager.default.contentsOfDirectory(atPath: unzipPath)
  } catch {
   return
  }

  for (index, item) in items.enumerated() {
   print("\(index)--文件名称---\(item)")
  }
 }

压缩和解压路径:

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
 }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们