通常我們為了節約流量,傳輸多個檔案的時候需要將它們打包成Zip檔案再傳輸,或者把下載下來的Zip包進行解壓。本文介紹如何使用 ZipArchive 進行檔案的壓縮、解壓操作。
1,SSZipArchive介紹
SSZipArchive是一個使用Objective-C編寫的在iOS、Mac下的壓縮、解壓縮工具類。
GitHub地址:https://github.com/ZipArchive/ZipArchive
功能如下:
(1)解壓zip檔案
(2)解壓帶密碼保護的zip檔案
(3)建立zip檔案
(4)添加新檔案到zip檔案中
(5)壓縮檔
(6)使用一個名字來壓縮NSData對象
2,SSZipArchive的安裝配置
(1)將下載下來的 SSZipArchive 檔案夾添加到項目中來
(2)建立橋接標頭檔 bridge.h 來包含需要引用的Objective-C標頭檔,內容如下:
#import "ZipArchive.h"
(3)在項目target -> Build Phases -> Link Binary With Libraries中點擊加號,添加 libz.dylib
3,使用範例
首先為了便於後面測試,我們先在項目中添加兩張圖片,以及兩個壓縮包檔案(其中 test_password.zip 是帶密碼的壓縮包,密碼是:hangge.com)
同時定義一個方法返回目標路徑(每次調用都會在程式的 Caches 下建立一個隨機檔案夾),為的是讓每次壓縮、解壓縮的目標儲存地址都不會衝突:
//在Caches檔案夾下隨機建立一個檔案夾,並返迴路徑
func tempDestPath() -> String? {
var path = NSSearchPathForDirectoriesInDomains(.CachesDirectory,
.UserDomainMask, true)[0]
path += "/\(NSUUID().UUIDString)"
let url = NSURL(fileURLWithPath: path)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(url,
withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
if let path = url.path {
print("path:\(path)")
return path
}
return nil
}
(1)解壓普通zip檔案
let zipPath = NSBundle.mainBundle().pathForResource("test", ofType: "zip")
SSZipArchive.unzipFileAtPath(zipPath, toDestination: tempDestPath())
(2)解壓帶密碼的zip檔案
let zipPath2 = NSBundle.mainBundle().pathForResource("test_password", ofType: "zip")
do {
try SSZipArchive.unzipFileAtPath(zipPath2, toDestination: tempDestPath(),
overwrite: true, password: "hangge.com")
} catch {
}
(3)將檔案打成壓縮包
let files = [NSBundle.mainBundle().pathForResource("logo", ofType: "png")!,
NSBundle.mainBundle().pathForResource("icon", ofType: "png")!]
let zipPath3 = tempDestPath()! + "/hangge.zip"
SSZipArchive.createZipFileAtPath(zipPath3, withFilesAtPaths: files)
當然我們也是可以給壓縮包加上密碼的:
SSZipArchive.createZipFileAtPath(zipPath3, withFilesAtPaths: files,
withPassword: "hangge.com")
(4)將整個檔案夾下的檔案打成壓縮包
//需要壓縮的檔案夾啊
let filePath:String = NSHomeDirectory() + "/Documents"
//先在該檔案夾下添加一個檔案
let image = UIImage(named: "logo.png")
let data:NSData = UIImagePNGRepresentation(image!)!
data.writeToFile(filePath + "/logo.png", atomically: true)
let zipPath5 = tempDestPath()! + "/hangge.zip"
SSZipArchive.createZipFileAtPath(zipPath5, withContentsOfDirectory: filePath)
同樣的,我門也可以添加密碼:
SSZipArchive.createZipFileAtPath(zipPath6, withContentsOfDirectory: filePath,
withPassword: "hangge.com") //帶密碼