Search code examples
objective-cswiftzipzipzap

Zip/Rar files with SWIFT


I am new to SWIFT and I just started implementing my first application for OS X. I created a simple project and decided Ill look into different frameworks for using zip/rar files. I started with ZipArchive as recommended but couldn't make it work in my project - didn't even compile (probably something wrong with my setup), I had similar experience with Objective-Zip and SSZipArchive. Finally I stumbled on the framework zip zap which attached to my project perfectly.

I looked into the examples:

ZZArchive* oldArchive = [ZZArchive archiveWithURL:[NSURL fileURLWithPath:@"/tmp/old.zip"] error:nil];
ZZArchiveEntry* firstArchiveEntry = oldArchive.entries[0];
NSLog(@"The first entry's uncompressed size is %lu bytes.", (unsigned long)firstArchiveEntry.uncompressedSize);
NSLog(@"The first entry's data is: %@.", [firstArchiveEntry newDataWithError:nil]);

but I couldn't make it work with SWIFT. The problem I faced is that I couldn't create a NSURL that worked with the ZZArchive.

let zip:ZZArchive = ZZArchive(NSURL(fileURLWithPath:"/Users/../tesData/test.zip"))

led to

fatal error: unexpectedly found nil while unwrapping an Optional value

and everything else I tried either didn't compile with a unwrapping error or compiled but on execution led to this error.

Can someone please either help me solve my unzipping problem, or lead me to a solution of how to zip/unzip/read zip/rar/cbr files with swift.


Solution

  • This should fix it

    var path = NSURL.fileURLWithPath("/Users/../tesData/test.zip")
    var archive: ZZArchive = ZZArchive(URL:(fileURLWithPath:path!), error: &err)
    

    Here is an implementation of zzzip in swift

        //Declare
        var err: NSError? = NSError()
        var path = NSURL.fileURLWithPath("/PathToZipFile/file.zip")
        var URL3 = NSURL.fileURLWithPath("/pathanywhereinsystemtosaveunzipedfolder/")
        var URL2 = NSURL.fileURLWithPath("/PathToUnzippedFile/file.xxx")
        var fileManager = NSFileManager.defaultManager() //1
        let archive: ZZArchive = ZZArchive(URL:(fileURLWithPath:path!), error: &err)//2-3
    
        //Create Folder
        fileManager.createDirectoryAtURL(URL3!, withIntermediateDirectories: true, attributes: nil, error: &err)
    
        //Write First entry of archive to file
        var k = archive.entries[0].newDataWithError(nil)
        k.writeToURL(URL2!, atomically: false)
    

    This works for small text files and images. it does have its limitations due to no errorchecking and only writing the first archive entery to a file. If any paths are wrong you will end with errors as soon as you try and compile.