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


基础教程推荐
猜你喜欢
- asm基础——汇编指令之in/out指令 2023-07-06
- R语言基于Keras的MLP神经网络及环境搭建 2022-12-10
- swift 字符串String的使用方法 2023-07-05
- R语言数可视化Split violin plot小提琴图绘制方法 2022-12-10
- R语言-如何将科学计数法表示的数字转化为文本 2022-11-23
- UEFI开发基础HII代码示例 2023-07-07
- swift版webview加载网页进度条效果 2023-07-05
- Go web部署报错panic: listen tcp xxxxxxx:8090: bind: cannot assign requested address 2023-09-05
- R包ggtreeExtra绘制进化树 2022-12-14
- ruby-on-rails-使用Nginx的Rails的多阶段环境 2023-09-21