iPhone: Downloading zip and extracting in main bundle subdirectory at runtime
I want to extend my iPhone app that the app downloads a zip file into a sub directory then extracts it and then load images which were inside the zip.
Any ideas how to unzip in run-time and the access the images? Wou开发者_高级运维ld be really happy for some idea.
Greetings,
I've used ZipArchive with success in the past.
It's pretty ligthweight and simple to use, supports password protection, multiple files inside a ZIP, as well as compress & decompress.
The basic usage is:
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"ZipFileName" ofType:@"zip"];
ZipArchive *zipArchive = [[ZipArchive alloc] init];
[zipArchive UnzipOpenFile:filepath Password:@"xxxxxx"];
[zipArchive UnzipFileTo:{pathToDirectory} overWrite:YES];
[zipArchive UnzipCloseFile];
[zipArchive release];
You cannot extract into your bundle. Use [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
to get the path to a directory you can write to.
You can use the code from http://code.google.com/p/ziparchive/ to extract files from the zip archive.
If you add ZipArchive
to your project, remember to also add the framework.
The correct framework is libz.dylib
. Latest version (Xcode 4.2) is 1.2.5.
(Add framework to the section with libraries in the build phases tab of your target.)
I suggest you to use ssziparchive bcoz it support both ARC
and Non ARC
project.
- Add
SSZipArchive.h
,SSZipArchive.m
, andminizip
to your project. - Add latest version of the
libz
(right now itslibz1.2.5
) library to your target.
You don't need to do anything regarding ARC
. SSZipArchive
will detect if you're not using ARC
and add the required memory management code.
And code will be like this:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// Unzipping
//If your zip is in document directory than use this code
NSString *zipPath = [documentsDirectory stringByAppendingPathComponent:@"mediadata.zip"];
//else if zip file is in bundle than use this code
NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"mediadata" ofType:@"zip"];
NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:@"MediaData"];
if( [SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath] != NO ) {
//unzip data success
//do something
NSLog(@"Dilip Success");
}else{
NSLog(@"Dilip Error");
}
精彩评论