iOS-下载并解压Zip文件

项目开发中,有时候需要下载Zip类文件,并对其解压。

步骤如下:

下载ZipArchive库

下载ZipArchive库,并将其添加到项目中,注意ZipArchive.mm是非ARC文件,需要加上“-fno-objc-arc”编译位。

添加libz.tbd库

添加系统库libz.tbd,ZipArchive依赖该库,如果没添加,在调用时,会报错:

Undefined symbols for architecture i386:
      "_crc32", referenced from:
          _unzReadCurrentFile in unzip.o
          -[ZipArchive addFileToZip:newname:] in ZipArchive.o
          _zipWriteInFileInZip in zip.o
      "_deflate", referenced from:
          _zipWriteInFileInZip in zip.o
          _zipCloseFileInZipRaw in zip.o
      "_deflateEnd", referenced from:
          _zipCloseFileInZipRaw in zip.o
      "_deflateInit2_", referenced from:
          _zipOpenNewFileInZip3 in zip.o
      "_get_crc_table", referenced from:
          _unzOpenCurrentFile3 in unzip.o
          _zipOpenNewFileInZip3 in zip.o
      "_inflate", referenced from:
          _unzReadCurrentFile in unzip.o
      "_inflateEnd", referenced from:
          _unzCloseCurrentFile in unzip.o
      "_inflateInit2_", referenced from:
          _unzOpenCurrentFile3 in unzip.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

调用

利用NSURLSession进行下载,完成后解压。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)downloadAndUnzip
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
_task = [session downloadTaskWithRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://...zip"]] completionHandler:
^(NSURL *location, NSURLResponse *response, NSError *error) {
ZipArchive *za = [ZipArchive new];
if([za UnzipOpenFile:location.path]){
if([za UnzipFileTo:文件夹名 overWrite:YES]){
//解压后的路径为:文件夹名/文件名
}
}
}];
[_task resume];
}
YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!