★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-qojhmbcw-mb.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
目錄:[Swift]通天遁地Swiftios
本文將演示如何建立和解壓一個包含密碼的壓縮包。git
首先確保在項目中已經安裝了所需的第三方庫。github
點擊【Podfile】,查看安裝配置文件。sql
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】swift
1 import UIKit 2 import Zip 3 4 class ViewController: UIViewController { 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 // Do any additional setup after loading the view, typically from a nib. 9 //加密壓縮 10 zipFileWithPassword() 11 //解壓加密壓縮 12 unzipFileWithPassword() 13 } 14 15 //加密壓縮 16 func zipFileWithPassword() 17 { 18 //添加一個異常捕捉語句,實現壓縮文件 19 do 20 { 21 //初始化一個字符串常量,表示項目中帶壓縮文件的路徑 22 let filePath = Bundle.main.url(forResource: "BankAndCity", withExtension: "sqlite")! 23 //得到沙箱目錄中,文檔文件的路徑 24 var documentsFolder = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0] 25 //在文檔文件路徑的末尾,添加文件的名稱,做爲壓縮後的文件所在的路徑。 26 documentsFolder = documentsFolder.appendingPathComponent("NewArchivedFile.zip") 27 //調用第三方類庫的壓縮文件的方法,將數據庫文件進行壓縮,並設置安全密碼。 28 //同時設置壓縮的模式爲最佳模式. 29 try Zip.zipFiles(paths: [filePath], zipFilePath: documentsFolder, password: "coolketang", compression: .BestCompression, progress: 30 { 31 (progress) -> () in 32 //壓縮的過程當中,在控制檯實時輸出壓縮的進度。 33 print(progress) 34 }) 35 //輸出壓縮後的文件所在的絕對路徑 36 print("destinationPath:\(documentsFolder)") 37 } 38 catch 39 { 40 print("Something went wrong") 41 } 42 } 43 44 //解壓加密壓縮 45 func unzipFileWithPassword() 46 { 47 //添加一個異常捕捉語句,實現解壓加密壓縮 48 do 49 { 50 //得到在沙箱目錄中,文檔文件夾的路徑 51 var documentsFolder = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0] 52 //在文檔文件路徑的末尾,添加文件的名稱,做爲在上一個方法中壓縮文件所在的位置 53 documentsFolder = documentsFolder.appendingPathComponent("NewArchivedFile.zip") 54 let documentsDirectory = NSHomeDirectory() + "/Documents/" 55 //初始化一個網址對象,做爲解壓後的文件的目標位置。 56 let destinationPath = URL(fileURLWithPath: documentsDirectory) 57 //調用第三方類庫的解壓文件的方法,設置解壓的密碼, 58 //將指定的壓縮文件,解壓到指定的文件夾。 59 try Zip.unzipFile(documentsFolder, destination: destinationPath, overwrite: true, password: "coolketang", progress: { (progress) -> () in 60 //並在控制檯輸出解壓進度 61 print(progress) 62 }) 63 //輸出解壓後的文件所在的絕對路徑 64 print("destinationPath:\(destinationPath)") 65 } 66 catch 67 { 68 print("Something went wrong") 69 } 70 } 71 72 override func didReceiveMemoryWarning() { 73 super.didReceiveMemoryWarning() 74 // Dispose of any resources that can be recreated. 75 } 76 }