您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 下載並解壓 Zip 資源到本地的完整流程

編輯:iOS 開發綜合

在 iOS 應用中,經常需要從伺服器下載壓縮過的資源包(例如圖片、聲音),再於本地解壓使用。整體思路可以拆成三步:

1. 從伺服器下載 zip 資源包到本地;
2. 將 zip 解壓到程式目錄;
3. 從程式目錄載入資源檔案。

一、下載 zip 資源

以下方法會先檢查檔案是否已存在,若無則從網路下載並寫入:

-(NSString*)DownloadTextFile:(NSString*)fileUrl  fileName:(NSString*)_fileName

{

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);

    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

    NSString *sandboxPath = NSHomeDirectory();

    NSString *documentPath = [sandboxPath  stringByAppendingPathComponent:@"TestDownImgZip.app"];

    NSString *FileName=[documentPath stringByAppendingPathComponent:_fileName];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:FileName])

    {

        return FileName;

    }else

    {

        NSURL *url = [NSURL URLWithString:fileUrl];

        NSData *data = [NSData dataWithContentsOfURL:url];

        [data writeToFile:FileName atomically:YES];

    }

    return FileName;

}

二、解壓 zip 包

借助 ZipArchive 元件即可輕鬆完成解壓:

- (void)OpenZip:(NSString*)zipPath  unzipto:(NSString*)_unzipto

{

    ZipArchive* zip = [[ZipArchive alloc] init];

    if( [zip UnzipOpenFile:zipPath] )

    {

        BOOL ret = [zip UnzipFileTo:_unzipto overWrite:YES];

        if( NO==ret )

        {

            NSLog(@"error");

        }

        [zip UnzipCloseFile];

    }

    [zip release];

}

三、呼叫函式

最後把下載與解壓串接起來,再從解壓後的路徑載入圖片:

- (IBAction)ShowImg:(id)sender {

    NSString *filePath = [self DownloadTextFile:@"https://www.xtox.net/img.zip" fileName:@"img.zip"];

    NSLog(filePath);

   

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);

    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

    NSString *sandboxPath = NSHomeDirectory();

    NSString *documentPath = [sandboxPath  stringByAppendingPathComponent:@"TestDownImgZip.app"];

   

    [self OpenZip:filePath unzipto:documentPath];

    self.imgView.image = [UIImage imageNamed:@"img/1.png"];

}

透過這套流程,就能實現資源的動態下載、離線快取與本地讀取,非常適合需要遠端更新素材的應用場景。

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