[Swift通天遁地]七、數據與安全-(9)文件的壓縮和解壓
阿新 • • 發佈:2019-01-24
git 控制 end dir recreate code add 字符串 fun
本文將演示使用開源類庫實現文件的壓縮和解壓操作。
首先確保在項目中已經安裝了所需的第三方庫。
點擊【Podfile】,查看安裝配置文件。
1 platform :ios, ‘12.0‘ 2 use_frameworks! 3 4 target ‘DemoApp‘ do 5 source ‘https://github.com/CocoaPods/Specs.git‘ 6 pod ‘Zip‘ 7 end
根據配置文件中的相關配置,安裝第三方庫。
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】
1 import UIKit2 //引入已經安裝的第三方類庫 3 import Zip 4 5 class ViewController: UIViewController { 6 7 override func viewDidLoad() { 8 super.viewDidLoad() 9 // Do any additional setup after loading the view, typically from a nib. 10 11 //添加一個異常捕捉語句,實現文件的解壓和壓縮 12 do13 { 14 //初始化一個字符串常量,表示項目中壓縮文件的路徑 15 let filePath = Bundle.main.url(forResource: "BankAndCity.sqlite", withExtension: "zip")! 16 17 //調用第三方類庫的解壓方法,對指定路徑的壓縮文件進行解壓操作 18 let unzipDirectory = try Zip.quickUnzipFile(filePath) 19 //在控制臺輸出解壓後的文件路徑 20 print("unzipDirectory:\(unzipDirectory)") 21 22 //調用第三方類庫的壓縮文件的方法,可以將多個文件,合並為一個壓縮包,並設置壓縮後的文件名稱。 23 let zipFilePath = try Zip.quickZipFiles([unzipDirectory], fileName: "archivedFile") 24 //在控制臺輸出壓縮後的文件路徑 25 print("zipFilePath:\(zipFilePath)") 26 } 27 catch 28 { 29 print("Something went wrong") 30 } 31 } 32 33 override func didReceiveMemoryWarning() { 34 super.didReceiveMemoryWarning() 35 // Dispose of any resources that can be recreated. 36 } 37 }
[Swift通天遁地]七、數據與安全-(9)文件的壓縮和解壓