有没有一个类可以使用Zlib压缩数据,或者直接使用zlib.dylib是我唯一的选择?
NSData+Compression是一个易于使用的NSData类别实现。
用法:
NSData* compressed = [myData zlibDeflate];
NSData* originalData = [compressed zlibInflate];
以下是对我有用的方法: 1)基于ZLib的Objective-Zip新位置:https://github.com/gianlucabertani/Objective-Zip
Podfile:
pod 'objective-zip', '~> 1.0'
#import "ViewController.h"
#import "Objective-Zip.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *path = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"test.zip"]];
OZZipFile *zipFile= [[OZZipFile alloc] initWithFileName:path
mode:OZZipFileModeCreate];
NSString *str = @"Hello world";
OZZipWriteStream *stream= [zipFile writeFileInZipWithName:@"file.txt"
compressionLevel:OZZipCompressionLevelBest];
[stream writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
[stream finishedWriting];
[zipFile close];
}
2) 其他基于zlib的库也可以正常工作。https://github.com/ZipArchive/ZipArchive
注意:有时需要将libz.tbd(zlib.dylib的新名称)添加到“链接二进制文件”中。
快速示例:
#import "SSZipArchive.h"
...
- (void)viewDidLoad {
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSError *error;
NSString *str = @"Hello world";
NSString *fileName = [docsDir stringByAppendingPathComponent:@"test.txt"];
BOOL succeed = [str writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (succeed){
NSString *path = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"test.zip"]];
[SSZipArchive createZipFileAtPath:path withFilesAtPaths:@[fileName]];
}
}
ZipWriteStream *stream = [zipFile writeFileInZipWithName:@"abc.txt" compressionLevel:ZipCompressionLevelBest];
[stream writeData:abcData];
[stream finishedWriting];
ZipFile *unzipFile = [[ZipFile alloc] initWithFileName:@"test.zip" mode:ZipFileModeUnzip];
NSArray *infos = [unzipFile listFileInZipInfos];
for (FileInZipInfo *info in infos) {
NSLog(@"- %@ %@ %d (%d)", info.name, info.date, info.size, info.level);
// Locate the file in the zip
[unzipFile locateFileInZip:info.name];
// Expand the file in memory
ZipReadStream *read = [unzipFile readCurrentFileInZip];
NSMutableData *data = [[NSMutableData alloc] initWithLength:256];
int bytesRead = [read readDataWithBuffer:data];
[read finishedReading];
}
Z_DATA_ERROR
(-3),则可能需要将-zlibInflate
中的inflateInit(&strm)
替换为inflateInit2(&strm, 16+MAX_WBITS)
。 - Mike Keskinov