项目中有时候需要文件下载解压,项目中选择了ZipArchive,实际使用也比较简单,直接调用解压和压缩方法即可.
压缩
1
2
3
4
5
6
7
8
9
10
|
@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!)" )
}
}
|
#解压
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@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)" )
}
}
|
压缩和解压路径:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.jianshu.com/p/05b060589fb2#