是否有一个类允许使用 Zlib 压缩数据,或者直接使用 zlib.dylib 是我唯一的可能性?
问问题
13915 次
3 回答
12
NSData+Compression 是一个易于使用的 NSData 类别实现。
用法:
NSData* compressed = [myData zlibDeflate];
NSData* originalData = [compressed zlibInflate];
于 2009-12-18T00:30:33.903 回答
1
这对我有用:1)基于 ZLib 的 Objective-Zip 新位置:https ://github.com/gianlucabertani/Objective-Zip
播客文件:
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 的新名称)添加到“Link Binary With Libraries”
快速示例:
#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]];
}
}
于 2017-09-27T21:13:30.783 回答
0
作为替代方案,还有objective-zip,即“以面向对象友好的方式包装ZLib 和MiniZip 的小型Cocoa/Objective-C 库”。
将文件写入“.zip”存档很简单,只需执行以下代码:
ZipWriteStream *stream = [zipFile writeFileInZipWithName:@"abc.txt" compressionLevel:ZipCompressionLevelBest];
[stream writeData:abcData];
[stream finishedWriting];
该库还允许读取“.zip”文件的内容,并枚举其中包含的文件。
列出“.zip”文件的内容是通过与以下类似的代码完成的。
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];
}
于 2011-09-19T17:24:49.330 回答