在 iOS 應用中,經常需要從伺服器下載壓縮過的資源包(例如圖片、聲音),再於本地解壓使用。整體思路可以拆成三步:
1. 從伺服器下載 zip 資源包到本地;
2. 將 zip 解壓到程式目錄;
3. 從程式目錄載入資源檔案。
以下方法會先檢查檔案是否已存在,若無則從網路下載並寫入:
-(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;
}
借助 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"];
}
透過這套流程,就能實現資源的動態下載、離線快取與本地讀取,非常適合需要遠端更新素材的應用場景。