Code Snippet: Decompressing a gzipped buffer.

The other day I was working with a web service that gzipped some of its replies. I needed something simple and robust that would gunzip an NSData without writing a file. When a little googling did not turn up a palatable solution, I implemented one of my own. I have made the code available on GitHub, but I also wanted to write a blog post about it, as there does seem to be a lot of confusion about how to use zlib to gunzip data.

Since the data I needed to gunzip would be held in an NSData I decided that using a category on NSData was “the way to go”. The header file NSData+IDZGunzip.h looks like this:

There’s not much to comment on here. This file adds a new method to NSData, gunzip and defines a constant IDZGunzipErrorDomain that will be used in error handling.

Ignoring error handling for the moment, the implementation file NSData+IDZGunzip.m looks like this:

Let’s take a closer look at this code. Lines 10-12 initialize the zlib stream structure and library for decompression. The 16 is a “magic” value that instructs zlib to expect gzip compressed data.

Lines 14-15 create an appropriately sized output buffer to receive the output data. The last 4 bytes of gzipped data contain the length of the uncompressed data as a little-endian 32-bit unsigned integer.

Lines 17-20 connect the input and output buffers to the stream.

Line 22 does the actual decompression. The Z_FINISH argument tells the library that this is the final (and in our case only) input buffer to force it flush all its output.

Line 24 releases any memory used by the library.

Finally, line 26 returns the output to the caller.

When we add in some error handling things are a little bit more complex, but not too much:

The finished code can be used as follows:

Get the code from GitHub at this URL:

About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Code Snippets. Bookmark the permalink.

One Response to Code Snippet: Decompressing a gzipped buffer.

  1. Pingback: .Zlib 副檔名解壓縮成 NSData – doSomeThing

Leave a Reply