Swift實(shí)現(xiàn)文件壓縮和解壓示例代碼
項(xiàng)目中有時(shí)候需要文件下載解壓,項(xiàng)目中選擇了ZipArchive,實(shí)際使用也比較簡(jiǎn)單,直接調(diào)用解壓和壓縮方法即可.
壓縮
@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
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
LeetCode?刷題?Swift?兩個(gè)數(shù)組的交集
這篇文章主要為大家介紹了LeetCode?刷題?Swift?兩個(gè)數(shù)組的交集示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
淺析Swift中struct與class的區(qū)別(匯編角度底層分析)
這篇文章主要介紹了Swift中struct與class的區(qū)別 ,本文從匯編角度分析struct與class的區(qū)別,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
Swift解決UITableView空數(shù)據(jù)視圖問(wèn)題的簡(jiǎn)單方法
這篇文章主要給大家介紹了關(guān)于Swift解決UITableView空數(shù)據(jù)視圖問(wèn)題的簡(jiǎn)單方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用swift具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2018-10-10
Swift代碼實(shí)現(xiàn)冒泡排序算法的簡(jiǎn)單實(shí)例
冒牌排序可謂最基本的排序算法之一,穩(wěn)定而沒(méi)有優(yōu)化空間:D 下面就一起來(lái)看一下Swift代碼實(shí)現(xiàn)冒泡排序算法的簡(jiǎn)單實(shí)例:2016-06-06
Swift?Sequence?Collection使用示例學(xué)習(xí)
這篇文章主要為大家介紹了Swift?Sequence?Collection使用示例學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07

