SSZipArchive解压缩官方demo地址https://github.com/ZipArchive/ZipArchive
一下文章主要是记录下看demo时的解压缩功能
1、压缩
_zipPath = [self tempZipPath];
- (NSString *)tempZipPath {
NSString *path = [NSString stringWithFormat:@"%@/%@.zip",
NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0],
[NSUUID UUID].UUIDString];
return path;
}
NSLog(@"Zip path: %@", _zipPath);
打印结果:Zip path: /Users/admin/Library/Developer/CoreSimulator/Devices/3E9F0B21-D9F9-4CB0-B9DC-DC7BEDC3DBFB/data/Containers/Data/Application/CE1DD483-E455-48C1-873F-4D83EE74920B/Library/Caches/3DCF2C1C-1C72-499F-AB28-C7F240B5FA09.zip
可以看到Zip path是“由沙盒路径和 [NSUUID UUID].UUIDString]”组成。其中/Users/admin/.../Library/Caches这部分是沙盒路径, 后部分是UUID。同时也看到了沙盒里的经常说的沙盒目录结构
(1)/AppName.app 应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以不能在运行时对这个目录中的内容进行修改,否则会导致应用程序无法启动。
(2)/Documents/ 保存应用程序的重要数据文件和用户数据文件等。用户数据基本上都放在这个位置(例如从网上下载的图片或音乐文件),该文件夹在应用程序更新时会自动备份,在连接iTunes时也可以自动同步备份其中的数据
(3)/Library 目录:这个目录下有两个子目录:
可创建子文件夹。可以用来放置您希望被备份但不希望被用户看到的数据。该路径下的文件夹,除Caches以外,都会被iTunes备份
- /Library/Caches(缓存) 保存应用程序使用时产生的支持文件和缓存文件(保存应用程序再次启动过程中需要的信息),还有日志文件最好也放在这个目录。iTunes 同步时不会备份该目录并且可能被其他工具清理掉其中的数据。
- /Library/Preferences (偏好)保存应用程序的偏好设置文件(使用 NSUserDefaults( 这个就是放这) 类设置时创建,不应该手动创建;连iTunes可备份,在应用程序更新时会自动备份;plist文件就放在此处)。
(4)/tmp/ 保存应用运行时所需要的临时数据,该路径下的文件不会被iTunes备份。iphone 重启时,会自动清除该目录下所有文件;例如录制视频完成后是放在/temp/;所以应该将视频文件从该文件夹转移到相册中,否则视频文件就会被系统清理掉
.
BOOL success = [SSZipArchive createZipFileAtPath:_zipPath
withContentsOfDirectory:_samplePath
keepParentDirectory:NO
compressionLevel:-1
password:password.length > 0 ? password : nil
AES:YES
progressHandler:nil];
2.解压
- (IBAction)unzipPressed:(id)sender {
if (!_zipPath) {
return;
}
NSString *unzipPath = [self tempUnzipPath];
NSLog(@"Unzip path: %@", unzipPath);
//打印结果:/Users/admin/Library/Developer/CoreSimulator/Devices/3E9F0B21-D9F9-4CB0-B9DC-DC7BEDC3DBFB/data/Containers/Data/Application/CE1DD483-E455-48C1-873F-4D83EE74920B/Library/Caches/77817AD7-9086-456B-835A-42EEE2461B7D
//新创建了一个“77817AD7-9086-456B-835A-42EEE2461B7D”的文件路径
if (!unzipPath) {
return;
}
NSString *password = _passwordField.text;
BOOL success = [SSZipArchive unzipFileAtPath:_zipPath
toDestination:unzipPath
preserveAttributes:YES
overwrite:YES
nestedZipLevel:0
password:password.length > 0 ? password : nil
error:nil
delegate:nil
progressHandler:nil
completionHandler:nil];
}
- (NSString *)tempUnzipPath {
NSString *path = [NSString stringWithFormat:@"%@/%@",
NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0],
[NSUUID UUID].UUIDString];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtURL:url
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (error) {
return nil;
}
return url.path;
}