項(xiàng)目中有時(shí)候需要文件下載解壓,項(xiàng)目中選擇了ZipArchive,實(shí)際使用也比較簡單笋除,直接調(diào)用解壓和壓縮方法即可.
壓縮
<pre><code>`
@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!)")
}
}`</code></pre>
解壓
<pre><code>`
@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)")
}
}`</code></pre>
壓縮和解壓路徑:
<pre><code>`
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
}`</code></pre>