Swift实现文件压缩和解压示例代码
2019/7/9 22:18:41
本文主要是介绍Swift实现文件压缩和解压示例代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
项目中有时候需要文件下载解压,项目中选择了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 }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于Swift实现文件压缩和解压示例代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-10-05Swift语法学习--基于协议进行网络请求
- 2022-08-17Apple开发_Swift语言地标注释
- 2022-07-24Swift 初见
- 2022-05-22SwiftUI App 支持多语种 All In One
- 2022-05-10SwiftUI 组件参数简写 All In One
- 2022-04-14SwiftUI 学习笔记
- 2022-02-23Swift 文件夹和文件操作
- 2022-02-17Swift中使用KVO
- 2022-02-08Swift 汇编 String array
- 2022-01-30SwiftUI3.0页面反向传值