Swift實現(xiàn)文件壓縮和解壓示例代碼
更新時間:2017年03月23日 09:17:48 作者:FlyElephant
本篇文章主要介紹了Swift實現(xiàn)文件壓縮和解壓示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
項目中有時候需要文件下載解壓,項目中選擇了ZipArchive,實際使用也比較簡單,直接調用解壓和壓縮方法即可.
壓縮
@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 }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Swift 3.0將UILabel數(shù)字顏色設置為紅色的方法
這篇文章主要介紹了關于在Swift中將UILabel數(shù)字顏色設置為紅色的方法,文中給出了詳細的示例代碼,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03舉例講解Swift編程中switch...case語句的用法
這篇文章主要介紹了Swift編程中switch...case語句的用法,其中fallthrough關鍵字在switch語句中的使用是重點,需要的朋友可以參考下2016-04-04