Swift实现文件压缩和解压示例代码
项目中有时候需要文件下载解压,项目中选择了ZipArchive,实际使用也比较简单,直接调用解压和压缩方法即可.
压缩
@IBActionfunczipAction(_sender:UIButton){
letimageDataPath=Bundle.main.bundleURL.appendingPathComponent("FlyElephant").path
zipPath=tempZipPath()
letsuccess=SSZipArchive.createZipFile(atPath:zipPath!,withContentsOfDirectory:imageDataPath)
ifsuccess{
print("压缩成功---\(zipPath!)")
}
}
#解压
@IBActionfuncunZipAction(_sender:UIButton){
guardletzipPath=self.zipPathelse{
return
}
guardletunzipPath=tempUnzipPath()else{
return
}
letsuccess=SSZipArchive.unzipFile(atPath:zipPath,toDestination:unzipPath)
if!success{
return
}
print("解压成功---\(unzipPath)")
varitems:[String]
do{
items=tryFileManager.default.contentsOfDirectory(atPath:unzipPath)
}catch{
return
}
for(index,item)initems.enumerated(){
print("\(index)--文件名称---\(item)")
}
}
压缩和解压路径:
functempZipPath()->String{
varpath=NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask,true)[0]
path+="/\(UUID().uuidString).zip"
returnpath
}
functempUnzipPath()->String?{
varpath=NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask,true)[0]
path+="/\(UUID().uuidString)"
leturl=URL(fileURLWithPath:path)
do{
tryFileManager.default.createDirectory(at:url,withIntermediateDirectories:true,attributes:nil)
}catch{
returnnil
}
returnurl.path
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下