本篇文章主要介绍了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 迭代器知识汇总 2023-07-23
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- Swift超详细讲解指针 2023-07-08
- Ruby的字符串与数组求最大值的相关问题讨论 2023-07-22
- 汇编语言程序设计之根据输入改变屏幕颜色的代码 2023-07-06
- Go Web开发进阶实战(gin框架) 2023-09-06
- R语言关于二项分布知识点总结 2022-11-30
- R语言-如何切换科学计数法和更换小数点位数 2022-11-23
- Golang http.Client设置超时 2023-09-05
- R语言绘图数据可视化pie chart饼图 2022-12-10