How to unzip a .zip file on iOS?
Use Zip Foundation if you are working in Swift language. It's easy to use and one of the best swift library for unzipping a zip file.
Zip:
let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("file.txt")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("archive.zip")
do {
try fileManager.zipItem(at: sourceURL, to: destinationURL)
} catch {
print("Creation of ZIP archive failed with error:\(error)")
}
UnZip:
let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("archive.zip")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("directory")
do {
try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
try fileManager.unzipItem(at: sourceURL, to: destinationURL)
} catch {
print("Extraction of ZIP archive failed with error:\(error)")
}
If you are using Objective-C then SSZipArchive is the best choice for this.
You can unzip using this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *outputPath = [documentsDirectory stringByAppendingPathComponent:@"/ImagesFolder"];
NSString *zipPath = Your zip file path;
[SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:self];
Hope it helps you.
There is a great 3rd party tool for zipping/unzipping files for iPhone
https://github.com/soffes/ssziparchive
Very simple to use. Hope that helps!!
Edit:
Quick method I created which takes url, downloads the zip and unzips it
-(void)downloadAndUnzip : (NSString *)sURL_p : (NSString *)sFolderName_p
{
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(q, ^{
//Path info
NSURL *url = [NSURL URLWithString:sURL_p];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *fileName = [[url path] lastPathComponent];
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:YES];
dispatch_async(main, ^
{
//Write To
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:sFolderName_p];
[SSZipArchive unzipFileAtPath:filePath toDestination:dataPath];
});
});
}