iOS 上有不少需要打包檔案的場景——批次上傳、備份使用者資料、下載後就地解開。第三方類別 ZipArchive 把這件事包得很省事,壓縮與解壓各只需數行。
ZipArchive* zipFile = [[ZipArchive alloc] init]; // 傳入必須是完整路徑,例如 /var/.../Documents/demo.zip [zipFile CreateZipFile2:@"zipfilename"]; // 若要加上密碼,改用這個版本 [zipFile CreateZipFile2:@"zipfilename" Password:@"your password"]; // 逐一加入要壓縮的檔案 // 第一個參數是完整路徑,例如 /var/.../Documents/a.txt // 第二個參數是該檔案在壓縮包內的名稱,只要檔名、不帶路徑 [zipFile addFileToZip:@"fullpath of the file" newname:@"new name of the file without path"]; // 要壓縮整個資料夾時,重複呼叫 addFileToZip 即可 [zipFile CloseZipFile2]; [zipFile release];
ZipArchive* zipFile = [[ZipArchive alloc] init]; [zipFile UnzipOpenFile:@"zip file name"]; // 同樣有帶密碼的版本 [zipFile UnzipOpenFile:@"zip file name" Password:@"password"]; // 解壓目標位置需為完整路徑 [zipFile UnzipFileTo:@"output path" overwrite:YES]; [zipFile UnzipCloseFile]; [zipFile release];
路徑一律要完整。無論 CreateZipFile2 還是 UnzipFileTo,參數都是絕對路徑。實務上先用 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, ...) 取得沙盒目錄,再用 stringByAppendingPathComponent: 組出路徑,比手寫字串安全得多。
Open 與 Close 必須成對。漏掉 Close 會讓檔案控制代碼與內部狀態沒有釋放,後續檔案操作可能出現難以追蹤的錯誤。
overwrite 參數要想清楚。設為 YES 會直接覆蓋同名的既有檔案。若解壓內容來自網路,建議先檢查目標目錄,避免覆蓋掉應用程式自己的資料。
記得釋放。上述為 MRC 寫法,用完要 release;ARC 專案則省略這一步。
密碼保護不等於加密。傳統 zip 的標準密碼機制強度有限,若 archive 內容敏感,應在檔案層或傳輸層另加上真正的加密(例如 HTTPS 傳輸,或先以 CommonCrypto 加密再打包)。
最後提醒,大量檔案的壓縮與解壓屬於 CPU 與 IO 密集工作,建議放到背景佇列執行,避免凍結主執行緒造成介面無回應。