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)文章
Swift 3.0將UILabel數(shù)字顏色設(shè)置為紅色的方法
這篇文章主要介紹了關(guān)于在Swift中將UILabel數(shù)字顏色設(shè)置為紅色的方法,文中給出了詳細(xì)的示例代碼,相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-03-03詳解Swift語(yǔ)言的while循環(huán)結(jié)構(gòu)
這篇文章主要介紹了Swift語(yǔ)言的while循環(huán)結(jié)構(gòu),包括do...while循環(huán)的用法,需要的朋友可以參考下2015-11-11舉例講解Swift編程中switch...case語(yǔ)句的用法
這篇文章主要介紹了Swift編程中switch...case語(yǔ)句的用法,其中fallthrough關(guān)鍵字在switch語(yǔ)句中的使用是重點(diǎn),需要的朋友可以參考下2016-04-04swift版webview加載網(wǎng)頁(yè)進(jìn)度條效果
這篇文章主要為大家詳細(xì)介紹了swift實(shí)現(xiàn)webview加載網(wǎng)頁(yè)進(jìn)度條效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11在Swift程序中實(shí)現(xiàn)手勢(shì)識(shí)別的方法
這篇文章主要介紹了在Swift程序中實(shí)現(xiàn)手勢(shì)識(shí)別的方法,蘋(píng)果的Swift語(yǔ)言即將進(jìn)入2.0開(kāi)源階段,人氣爆棚中:D 需要的朋友可以參考下2015-07-07Swift 基本數(shù)據(jù)類型詳解總結(jié)
在我們使用任何程序語(yǔ)言編程時(shí),需要使用各種數(shù)據(jù)類型來(lái)存儲(chǔ)不同的信息。變量的數(shù)據(jù)類型決定了如何將代表這些值的位存儲(chǔ)到計(jì)算機(jī)的內(nèi)存中。在聲明變量時(shí)也可指定它的數(shù)據(jù)類型。所有變量都具有數(shù)據(jù)類型,以決定能夠存儲(chǔ)哪種數(shù)據(jù)2021-11-11Swift實(shí)現(xiàn)簡(jiǎn)易計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了Swift實(shí)現(xiàn)簡(jiǎn)易計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01