#import <zlib.h>
Compression
-(NSData *) Compressdata: (NSData *) uncompresseddata{if ([uncompresseddata length] = = 0) return uncompresseddata; Z_stream STRM; Strm.zalloc = Z_null; Strm.zfree = Z_null; Strm.opaque = Z_null; strm.total_out = 0; strm.next_in= (BYTEF *) [uncompresseddata bytes]; strm.avail_in = (unsigned int) [uncompresseddata length]; if (DeflateInit2 (&STRM, Z_default_compression, z_deflated, (15+16), 8, z_default_strategy)! = Z_OK) return nil; Nsmutabledata *compressed = [Nsmutabledata datawithlength:16384]; 16K chunks for expansion do {if (strm.total_out >= [Compressed length]) [Compresse D increaselengthby:16384]; Strm.next_out = [Compressed mutablebytes] + strm.total_out; Strm.avail_out = (unsigned int) ([compressed length]-strm.total_out); Deflate (&STRM, z_finish); } while (strm.avail_out = = 0); Deflateend (&STRM); [Compressed SETLENGTH:STRM.total_out]; return [NSData datawithdata:compressed];}
Unzip
-(NSData *) Uncompresszippeddata: (NSData *) Compresseddata {if ([compresseddata length] = = 0) return Compressedd Ata unsigned full_length = [compresseddata length]; unsigned half_length = [Compresseddata length]/2; Nsmutabledata *decompressed = [Nsmutabledata datawithlength:full_length + half_length]; BOOL done = NO; int status; Z_stream STRM; strm.next_in = (BYTEF *) [compresseddata bytes]; strm.avail_in = [Compresseddata length]; strm.total_out = 0; Strm.zalloc = Z_null; Strm.zfree = Z_null; if (InflateInit2 (&STRM, (15+32)) = Z_OK) return nil; while (!done) {//Do sure we have enough and reset the lengths. if (strm.total_out >= [decompressed length]) {[decompressed increaselengthby:half_length]; } strm.next_out = [decompressed mutablebytes] + strm.total_out; Strm.avail_out = [decompressed length]-strm.total_out; Inflate another chunk. Status = Inflate (&STRM, Z_sync_flush); if (status = = Z_stream_end) {done = YES; } else if (status! = Z_OK) {break; }} if (Inflateend (&STRM)! = Z_OK) return nil; Set real length. if (done) {[decompressed setLength:strm.total_out]; return [NSData datawithdata:decompressed]; } else {return nil; } }
iOS compression decompression