How to unzip a .zip file on iOS?

openfrog picture openfrog · Apr 19, 2013 · Viewed 32k times · Source

After StoreKit downloads the IAP content package it returns an NSURL to me which looks like this:

file://localhost/private/var/mobile/Applications/45EF2B3A-3CAB-5A44-4B4A-631A122A4299/Library/Caches/BA32BC55-55DD-3AA4-B4AC-C2A456622229.zip/

Despite all sources I found claiming that StoreKit unzips the content package once downloaded, it hands me over a ZIP. This ZIP probably contains the file structure of the content package. But how do I unzip this?

Answer

Nishant Tyagi picture Nishant Tyagi · Apr 19, 2013

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.