Monday, July 24, 2017

Compress File(s) with using Minizip and ZipArchive – iPhone / iPad

Here's a simple class for compressing and extracting files. Its work depends on minizip, which is a open source zip format library.

The major class name is ZipArchive, it’s easy to use, you can declare a instance and call initialize functions, and then call addFileToZip or UnzipFileTo to finish compression or uncompression. Lets see how to use it.

------------------------------
First download ZipArchive and Minizip from here.

Add all the files to you project, and and framework libz.1.2.3.dylib

Include ZipArchive.h using #import "ZipArchive/ZipArchive.h" or #import "ZipArchive.h"

------------------------------

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//get app’s documents directory

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *tmpPathToFile = [documentsDirectory stringByAppendingPathComponent:@"mypicture.jpg"];

//you can give any name to zip file and ZipArchive will save the zip file to your app’s document directory.

NSString *zipFileTo = [documentsDirectory stringByAppendingPathComponent:@"mycompressedfile.zip"];

ZipArchive *zip = [[ZipArchive alloc] init];

BOOL result = [zip CreateZipFile2:zipFileTo];

//add only one file

ret = [zip addFileToZip:tmpPathToFile newname:@"mypicture.png"];

//add multiple files to your zip file. sample “files” array is an NSMutableArray and it contains only file name like, “mypicture1″, “mypicture2″

for (int i = 0; i<[files count]; i++) {

//physical path of your file

NSString *otherFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[files objectAtIndex:i]]];

//add the file with new name

ret = [zip addFileToZip:otherFiles newname:[NSString stringWithFormat:@"%@.png",[files objectAtIndex:i]]];

}

BOOL success = [zip CloseZipFile2];

[zip release];