(一二九)获取文件的MineType、利用SSZipArchive进行压缩解压

MineType简介

文件在网络上以二进制流的方式传播,为了区分不同的文件类型,用MineType来标明。

为什么要获取

文件的拓展名较短,比较好记,但是MineType是很长的,比如docx拓展名的MineType是application/vnd.openxmlformats-officedocument.wordprocessingml.document,,因此比较合适的方案是根据拓展名直接得到MineType。

怎么做

比较幸运,通过URLConnection的响应体response就能拿到MineType,我们只需要把获取本地文件包装成一个URL请求,然后拿到response即可,代码如下:

NSURL *url = [[NSBundle mainBundle] URLForResource:@”test” withExtension:@”docx”];NSURLRequest *request = [NSURLRequest requestWithURL:url];[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {NSLog(@”%@”,response.MIMEType);}];文件的压缩与解压第三方框架

SSZipArchive是一个用于ZIP压缩与解压的第三方框架,可作为工具类使用,十分方便。

导入

下载完毕后,将minizip文件夹与SSZipArchive类文件导入工程,并且添加动态库libz.dylib(在Build Phases的Link Binary With Libraries中添加)。

使用

通过类方法createZipFileAtPath:withFilesAtPaths:和unzipFileAtPath:toDestination:分别可以实现压缩和解压。假设现在工程中有4_7inch1.jpg~4_7inch4.jpg四个文件,下面的代码在触摸开始时对他们进行压缩,并保存在沙盒的Library/Caches中;在触摸结束时将其解压。

注意解压时应该指定一个目录,否则会在当前目录解压所有文件。通过类方法的返回值可以判断操作是否成功。

代码如下:

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSMutableArray *paths = [NSMutableArray array];for (int i = 1; i <= 4; i++) {NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@”4_7inch%d.jpg”,i] ofType:nil];[paths addObject:path];}NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *outPath = [cachePath stringByAppendingPathComponent:@”imgs.zip”];if([SSZipArchive createZipFileAtPath:outPath withFilesAtPaths:paths]){NSLog(@”success”);} }- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *zipPath = [cachePath stringByAppendingPathComponent:@”imgs.zip”];if ([SSZipArchive unzipFileAtPath:zipPath toDestination:[cachePath stringByAppendingPathComponent:@”imgs/”]]) {NSLog(@”success”);} }

只有经历过地狱般的折磨,才有征服天堂的力量。

(一二九)获取文件的MineType、利用SSZipArchive进行压缩解压

相关文章:

你感兴趣的文章:

标签云: