Server Side Swift Basics — Zipping directories

Jonathan Guthrie
Server Side Swift and More
3 min readApr 7, 2017

Taking a step away from sending files over HTTP for a few minutes of light reading, and lets look at how to take a directory, and zip it with Swift on the server.

I’m going to show you how to do this in an isolated way, but if you have an existing Swift server app you can easily add this into your existing codebase.

So lets start with a basic swift app, with absolutely nothing in it.

mkdir ziptest
cd ziptest
swift package init
The directory generated by “swift package init”

First, in that new directory, lets make a new directory that we want to zip, and put a random text file in there:

Next, lets add the library to the Package.swift file…
Add to the dependencies array:

.Package(url: “https://github.com/PerfectlySoft/Perfect-Zip.git", majorVersion: 2)

OK so lets rename ziptests.swift to main.swift (so that it is recognized as an executable) then open and remove the placeholder content.

We only need a few things in here:

import PerfectZip// the zip object
let zippy = Zip()
// zip the files, in the source directory,
// into the destination file, overwriting any existing file.
let zipResult = zippy.zipFiles(paths: ["./randomzip"], zipFilePath: "./randomzip.zip", overwrite: true, password: "")
// ZipResult contains the enum with the result of the operation.
print(zipResult == .ZipSuccess, zipResult.description)

Now lets execute our little application… “swift build”, then “.build/debug/ziptests”

Building in the terminal, then running.
And there’s our new file.

Now, to unzip is almost exactly the same:

// instantiate the zip object
let unZippy = Zip()
// unzip the file, into the destination directory, overwrite enabled
let UnZipResult = unZippy.unzipFile(source: "./randomzip.zip", destination: "./randomzip2", overwrite: true)
// UnZipResult contains the result of the operation
print(UnZipResult == .ZipSuccess, UnZipResult.description)

Building and running this again, we see:

true Success.
true Success.

And looking at the directory now, there’s a new dir containing the unzipped directory. Easy.

For examples visit GitHub.com/perfectexamples — there is an ever growing library of examples and demos there.

And of course if you’re looking for live help from our awesome community, join our Slack channel via www.perfect.ly

Thanks for being with us today, don’t forget to say Hi on Slack!

--

--

Jonathan Guthrie
Server Side Swift and More

Developer Evangelist, Musician, and Active Activist... Newmarket ON, Canada