本篇文章主要介绍了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实现文件压缩和解压示例代码
基础教程推荐
猜你喜欢
- Go语言实现一个Http Server框架(二) Server的抽象 2023-07-25
- R语言学习代码格式一键美化 2022-12-05
- R语言histogram(直方图)的具体使用 2022-10-28
- golang 自然语言处理工具(gohanlp) 2023-09-05
- go语言的魔幻旅程14-反射 2023-09-05
- ruby-on-rails – Nginx支持的Rails应用程序中缺少Content-Length Header 2023-09-20
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- R语言使用gganimate创建可视化动图 2022-12-10
- R语言多元线性回归实例详解 2022-12-15
- R语言关联规则深入详解 2022-11-08
