本篇文章主要介绍了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实现文件压缩和解压示例代码


基础教程推荐
猜你喜欢
- ruby-on-rails-为使用Rails 4,nginx和乘客的用户设置自定义域 2023-09-21
- R语言-修改(替换)因子变量的元素操作 2022-11-26
- Ruby3多线程并行Ractor使用方法详解 2023-07-23
- ruby on rails validates 2023-09-22
- 浅析ELF转二进制允许把 Binary 文件加载到任意位置 2023-07-06
- win10下使用virtualbox + vagrant配置ruby开发机环境 2023-07-23
- R语言 ggplot2改变柱状图的顺序操作 2022-11-17
- R语言绘制折线图实例分析 2022-11-21
- Swift初始化器与可选链的使用方法介绍 2023-07-08
- Swift中重写和重载的使用与对比总结 2023-07-05