Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compress data using Zlib, without directly using zlib.dylib?

Is there a class that allows compressing data using Zlib, or is using zlib.dylib directly the only possibility I have?

like image 583
apaderno Avatar asked Dec 17 '09 22:12

apaderno


2 Answers

NSData+Compression is an easy to use NSData category implementation.

  • NSData+Compression.h
  • NSData+Compression.m

Usage:

NSData* compressed = [myData zlibDeflate];
NSData* originalData = [compressed zlibInflate];
like image 84
vaddieg Avatar answered Nov 15 '22 09:11

vaddieg


Here is what worked for me: 1) ZLib based Objective-Zip new location: https://github.com/gianlucabertani/Objective-Zip

Podfile:

pod 'objective-zip', '~> 1.0'

Quick example:

#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) Other zlib based library worked fine too. https://github.com/ZipArchive/ZipArchive

note: sometimes it's needed to add libz.tbd (new name of zlib.dylib) to "Link Binary With Libraries"

Quick example:

#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]];
    }
}
like image 41
Andrew Terekhine Avatar answered Nov 15 '22 08:11

Andrew Terekhine