文件压缩与解压缩:(用到框架SSZipArchive-master)
注意:需要引入libz.dylib框架
- 1,文件压缩比较简单,直接用框架创建对象,然后传入需压缩文件地址和目标文件地址即可(注意:这个压缩是同步压缩,可以有返回值),如果需要设置密码,换另外一种创建方法即可
- 方法
//传入所有文件路径,是一个数组
+ (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray *)filenames;
//传入文件夹路径,是一个字符串
+ (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath;
- 使用:
//需压缩文件地址
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//目标文件地址
NSString *images = [caches stringByAppendingPathComponent:@"images.zip"];
[SSZipArchive createZipFileAtPath:images withContentsOfDirectory:caches];
-
2,解压缩也差不多:第一个方法不设置密码,第二个方法设置密码
-
方法:
//直接接压缩即可,暂时不明白最后一个Id是干嘛的
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination uniqueId:(NSString *)uniqueId;
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error uniqueId:(NSString *)uniqueId;
//需要用到代理方法
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination delegate:(id<SSZipArchiveDelegate>)delegate uniqueId:(NSString *)uniqueId;
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error delegate:(id<SSZipArchiveDelegate>)delegate uniqueId:(NSString *)uniqueId;
- 使用:
NSURL *url = [NSURL URLWithString:@"http://192.168.1.100:8080/MJServer/resources/videos/zhang.zip"];
NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
[SSZipArchive unzipFileAtPath:location.path toDestination:caches uniqueId:@"1"];
NSLog(@"zhang");
}];
[task resume];
- 3,通过代理方法监听压缩或者解压缩的过程
//将要开始解压缩
- (void)zipArchiveWillUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo{
NSLog(@"%@---zipArchiveWillUnzipArchiveAtPath",path);
}
//将要解压缩压缩文件中的第fileIndex个文件
- (void)zipArchiveWillUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo{
NSLog(@"zipArchiveWillUnzipFileAtIndex---%ld",(long)fileIndex);
}
//压缩文件中的第fileIndex个文件解压完成
- (void)zipArchiveDidUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo{
NSLog(@"zipArchiveDidUnzipFileAtIndex");
}
//全部解压完成
- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPat uniqueId:(NSString *)uniqueId{
NSLog(@"zipArchiveDidUnzipArchiveAtPath");
}
网友评论