Как я могу создать ZIP-файл с помощью Objective C?
Я разрабатываю приложение для iOS и пытаюсь заархивировать файл, созданный в приложении, есть ли встроенная функция, способная сделать это?
4 ответа
Как указал Алекс, я ответил на этот вопрос, указав категорию NSData, предоставленную пользователями вики Cocoadev. Эта категория включает в себя методы для работы с заархивированными и сжатыми данными в экземпляре NSData (который может быть прочитан из файла Zip или записан в один). Это должно быть все, что вам нужно для реализации файла, который вы описываете, если вы можете передать данные вашего файла в экземпляр NSData.
Пример этой категории в действии приведен в исходном коде моего приложения для iPhone, Molecules. Я использую метод только для извлечения данных из сжатого файла (в SLSMolecule+PDB.m), но вы должны быть в состоянии получить основные понятия из этого.
Я определенно рекомендую Objective-Zip. Недавно он перешел на https://github.com/flyingdolphinstudio/Objective-Zip:
Некоторые примеры из их документации:
Создание Zip-файла:
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:@"test.zip" mode:ZipFileModeCreate];
Добавление файла в zip-файл:
ZipWriteStream *stream= [zipFile writeFileInZipWithName:@"abc.txt" compressionLevel:ZipCompressionLevelBest];
[stream writeData:abcData];
[stream finishedWriting];
Чтение файла из zip-файла:
ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:@"test.zip" mode:ZipFileModeUnzip];
[unzipFile goToFirstFileInZip];
ZipReadStream *read= [unzipFile readCurrentFileInZip];
NSMutableData *data= [[NSMutableData alloc] initWithLength:256];
int bytesRead= [read readDataWithBuffer:data];
[read finishedReading];
Сначала вы загружаете пример Objective-zip с http://code.google.com/p/objective-zip/downloads/list
В этом примере найдите и скопируйте три папки Objective-Zip, MiniZip и ZLib и перетащите их в свой проект.
импортировать два класса в вас.m класс "ZipFile.h" и "ZipWriteStream.h"
создать метод почтового индекса мой код:
-(IBAction)Zip{
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory , NSUserDomainMask, YES);
NSString *ZipLibrary = [paths objectAtIndex:0];
NSString *fullPathToFile = [ZipLibrary stringByAppendingPathComponent:@"backUp.zip"];
//[self.fileManager createDirectoryAtPath:fullPathToFile attributes:nil];
//self.documentsDir = [paths objectAtIndex:0];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:fullPathToFile mode:ZipFileModeCreate];
NSError *error = nil;
self.fileManager = [NSFileManager defaultManager];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths1 objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:self.documentsDir error:&error];
//for(NSString *filename in files){
for(int i = 0;i<files.count;i++){
id myArrayElement = [files objectAtIndex:i];
if([myArrayElement rangeOfString:@".png" ].location !=NSNotFound){
NSLog(@"add %@", myArrayElement);
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(@"%d",data);
[streem writeData:data];
[streem finishedWriting];
}else if([myArrayElement rangeOfString:@".txt" ].location !=NSNotFound)
{
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(@"%d",data);
[streem writeData:data];
[streem finishedWriting];
}
}
[self testcsv];
[zipFile close];
}
в папке с документами сохранены файлы.png и.txt, архивируемые в папке Library с backup.zip. Надеюсь, это поможет
Не уверен, что есть встроенная функция, но, возможно, вы могли бы использовать внешнюю библиотеку, такую как InfoZip. Или же вы можете попробовать реализовать свою собственную библиотеку zip, я уверен, что спецификацию формата Zip можно найти где-нибудь в Интернете.
RWendi