近期的案子須把整體軟體的容量維持在10MB以下,換句話說,使用者從APP Store下載此APP,會得到一個10MB以下的軟體,登入帳號之後,會再從某伺服器下載完整的資料到APP,以獲得軟體應有的功能!
於是乎,建立與解除壓縮檔 (Zip and Unzip)派上用場~
很感謝已有前人將功能實作出來,我們只要知道如何使用自如即可~作者的網站就在文章下方的參考連結,我將使用方法簡潔記錄下來。
使用方式:
- Add all the files to you project, and and framework libz.1.2.5.dylib.
- Include ZipArchive.h using #import "ZipArchive/ZipArchive.h"
建立壓縮檔
- (BOOL)zipArchive
{
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
// 想要創造的ZIP檔的路徑
NSString *zipPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"zipFile.zip"]];
ZipArchive *zip = [[ZipArchive alloc] init];
[zip CreateZipFile2:zipPath Password:@""];
for (int i = 0; i < [self.happyImage count]; i++) {
// 想要加入的檔案的路徑
NSString *path = [documentsDirectory stringByAppendingPathComponent:self.happyImage[i]];
// newname參數為在ZIP檔中的新名稱
if (![zip addFileToZip:path newname:[NSString stringWithFormat:@"%i.jpg",(i + 1)]])
{
// 加入檔案失敗的處理~
}
}
BOOL success = [zip CloseZipFile2];
return success;
}
解除壓縮檔
- (BOOL)unzipArchive
{
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
// 想要解除的ZIP檔的路徑
NSString *zipPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"zipFile.zip"]];
ZipArchive *zip = [[ZipArchive alloc] init];
if ([zip UnzipOpenFile:zipPath Password:@""])
{
if (![zip UnzipFileTo:documentsDirectory overWrite:YES]) {
// 解壓縮失敗的處理~
}
}
BOOL success = [zip UnzipCloseFile];
return success;
}
準備好檔案,輸入/輸出檔案們的路徑,輸出/輸入壓縮檔的路徑,可選擇性加上密碼。
因為這個開源還沒有使用ARC,所以我們必須在專案中Build Phases設定Compile Sources,找到我們剛才加入的檔案,接著個別檔案設定Compiler Flages為-fno-objc-arc,即可成功通過編譯!
參考:ziparchive – An Objective C class for zip/unzip on iPhone and Mac OSX – Google Project Hosting、Migrating your code to Objective-C ARC。

Comments on: "[iOS] 建立與解除壓縮檔 (Zip and Unzip)" (1)
[…] 想要複製Core Data,必須先知道它的位置所在,沒想到它有三個檔案:coredata.splite、coredata.splite-shm、coredata.splite-wal⋯⋯為了不遺漏任何一個相關檔案,我就把它們三個打包成zip檔。若要使用zip檔方式可參考我之前的文章-建立和解除壓縮檔。 […]
讚讚