/**
* 压缩文件的步骤,首先需要把zipArchive导入工程中,并添加 库 libz.dylib
*
* 创建压缩文件:
* 1.制定一个路径
* 2.利用方法 CreateZipFile2:创建压缩文件
* 3.利用方法 CreateZipFile2: Password:创建带有密码的压缩文件
* 4.给压缩文件中添加 文件
* 4.关闭 CloseZipFile2(只有调用了这个方法,zip文件才会从内存中写入磁盘)
*
* 解压文件:
* 1. 解压文件:UnzipOpenFile:
* 2. 把解压的文件存放到一个制定的目录:UnzipFileTo: overWrite:
* 3. 解压带有密码的文件
*
* 难点:
* 文件路径错误,会导致意想不到的错误
*
* 代码说明:
* 下面的代码主要的应用场景是,从网络上请求数据写入到压缩文件中,对这个压缩文件解压,得到一个密码和另外一个压缩文件,拿到密码后
* 对得到的压缩文件进行解压。
*/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths firstObject];
NSString *filepath = [documentPath stringByAppendingPathComponent:@"wsy.zip"];
NSString *encrypt = [documentPath stringByAppendingPathComponent:@"encrypt"];
NSString *filepath2 = [documentPath stringByAppendingPathComponent:@"wsy/wsy.zip"];
NSString *content = [documentPath stringByAppendingPathComponent:@"wsy/content"];
NSString *image = [documentPath stringByAppendingPathComponent:@"wsy/image.jpg"];
// 在documents下创建一个文件
// ~~~~~~/documents/firmail
NSString *firmailPath = [documentPath stringByAppendingPathComponent:@"wsy"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:firmailPath withIntermediateDirectories:YES attributes:nil error:nil];
ZipArchive *zip2 = [[ZipArchive alloc] init];
// 创建压缩文件,带有密码
BOOL ret3 = [zip2 CreateZipFile2:filepath2 Password:@"wsy"];
// 路径:documents/firmail/firmail.zip
// 把content和attachments/img.jpg加入到压缩文件中
// firmail.zip中包含了content和ttachments/img.jpg这两个文件
// 给压缩文件中添加内容
ret3 = [zip2 addFileToZip:content newname:@"content"];
ret3 = [zip2 addFileToZip:image newname:@"attachments/img.jpg"];
if (![zip2 CloseZipFile2]) {
filepath2 = @"";
}
ZipArchive *archive = [[ZipArchive alloc] init];
// 创建不带密码的压缩文件
ret3 = [archive CreateZipFile2:filepath];
// 路径:documents/firmail.zip
// 把 encrypt 和 firmail.zip 加入到压缩文件中
// firmail.zip中包含了content和firmail.zip这两个文件
ret3 = [archive addFileToZip:encrypt newname:@"encrypt"];
ret3 = [archive addFileToZip:filepath2 newname:@"wsy.zip"];
ret3 = [archive addFileToZip:[documentPath stringByAppendingPathComponent:@"image"] newname:@"header.jpg"];
if (![archive CloseZipFile2]) {
filepath2 = @"";
}
// 解压文件
ZipArchive *unZip = [[ZipArchive alloc] init];
// 把解压文件放入到这个路径下
NSString *unZipPath = [documentPath stringByAppendingPathComponent:@"wsy"];
ret3 = [unZip UnzipOpenFile:filepath];
if (ret3) {
// 把解压文件放入到一个路径下
ret3 = [unZip UnzipFileTo:unZipPath overWrite:YES];
if (ret3) {
NSLog(@"解压成功");
NSString *unzipPath2 = [unZipPath stringByAppendingPathComponent:@"wsy"];
NSString *secretFirmailZip = [unZipPath stringByAppendingPathComponent:@"wsy.zip"];
ZipArchive *unZipSecretFrimail = [[ZipArchive alloc] init];
if ([unZipSecretFrimail UnzipOpenFile:secretFirmailZip]) {
ret3 = [unZipSecretFrimail UnzipFileTo:unzipPath2 overWrite:YES];
if (ret3) {
NSLog(@"二次解压成功");
}
}
}else{
NSLog(@"解压失败");
}
// 关闭解压
[unZip UnzipCloseFile];
}