您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 下載 ZIP 資源包並解壓使用的完整實作

編輯:iOS 相關資訊

把圖片、音效等資源打包成 zip 下載,再於本地解壓使用,是變更 App 資源內容時不必重新上架的常見手法。整個流程分為三步。

一、下載 zip 檔

- (NSString *)downloadFileWithURL:(NSString *)fileUrl fileName:(NSString *)fileName {
    // NSSearchPathForDirectoriesInDomains 取得沙盒目錄全路徑
    NSString *documentPath =
        [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *targetPath = [documentPath stringByAppendingPathComponent:fileName];

    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:targetPath]) {
        return targetPath;      // 已存在則直接回傳,避免重複下載
    }

    NSURL *url = [NSURL URLWithString:fileUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    [data writeToFile:targetPath atomically:YES];
    return targetPath;
}

這裡有兩個必須注意的問題。第一,dataWithContentsOfURL: 是同步呼叫,會封鎖主執行緒;檔一大畫面就會卡住甚至被 watchdog 判定無回應而終止。實務上應改用 NSURLSession 的非同步 API。第二,用「檔案是否存在」當快取依據有風險:如果上次下載到一半失敗,殘缺檔案會被誤判為有效。較嚴謹的做法是比對版本號或 ETag。

二、解壓

- (void)unzipFileAtPath:(NSString *)zipPath toDirectory:(NSString *)dest {
    ZipArchive *zip = [[ZipArchive alloc] init];
    if ([zip UnzipOpenFile:zipPath]) {
        BOOL ret = [zip UnzipFileTo:dest overWrite:YES];
        if (NO == ret) {
            NSLog(@"解壓失敗");
        }
        [zip UnzipCloseFile];
    }
}

ZipArchive 是常見的第三方壓縮庫。若不想引入外部依賴,蘋果從 iOS 9 起提供了 NSFileManager 的 createZipFileAtPath:contentsOfDirectory: 與 unzipFileAtPath:toDestination:(實作於 Foundation 的 Archive 支援中,部分版本需搭配 SSZipArchive 等替代方案)。目前最主流的選擇是 SSZipArchive,API 簡潔且持續維護:

[SSZipArchive unzipFileAtPath:zipPath toDestination:dest];

三、呼叫並使用資源

- (IBAction)showImage:(id)sender {
    NSString *filePath = [self downloadFileWithURL:@"https://www.xtox.net/img.zip"
                                         fileName:@"img.zip"];
    NSString *documentPath =
        [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    [self unzipFileAtPath:filePath toDirectory:documentPath];
    self.imageView.image = [UIImage imageNamed:@"img/1.png"];
}

四、幾個實務上的重要修正

1. 不要解壓到 .app 目錄。 原範例把 TestDownImgZip.app 拼在路徑上,那是程式安裝包,屬於唯讀且受簽章保護的區域,寫入會失敗,App 也可能無法啟動。所有可寫資料都應放在 Documents、Library/Caches 或 tmp。

2. 下載要非同步並處理錯誤。 建議改用 NSURLSession 的 downloadTask,並在 completionHandler 中處理 nil、HTTP 狀態碼與網路錯誤。

3. 用 imageNamed: 讀不到動態解壓的圖。 imageNamed: 會從 main bundle 的快取中查找,解壓到 Documents 的檔案不在其中。應改用:

NSString *path = [[documentPath stringByAppendingPathComponent:@"img/1.png"]];
UIImage *image = [UIImage imageWithContentsOfFile:path];

4. 安全性。 從網路下載的 zip 若不驗證,可能成為攻擊途徑(例如路徑穿越攻擊,把檔案寫到預期之外的目錄)。使用前應確認解壓後的檔名不含 ../,重要資源建議加簽章或 checksum 驗證。

5. App Store 審核。 動態下載「可執行內容」是禁止的,但下載圖片、音效、設定等純資源資料是被允許的。界線在於下載的內容是否會改變 App 的行為邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved