Sunday 21 February 2021

Interop NSData compressed / decompressed on iOS with Inflater / Deflater on Android

With iOS 13 Apple added some convenience methods to NSData to compress and decompress data using a set of compression algorithms. Zlib is recommended as the cross-platform option for interoperating with non-Apple platforms. I recently had need of compressing data while supporting iOS & Android, I did not find much in the way of documented resources to achieve this, so this post is to document what I found.

Compressing Data

The zlib standard supports different levels of compression (an integer between 0 and 9) that tradeoff the speed verses the output size. On iOS the level is fixed to 5 and can not be changed. While with Android the developer can specify any of the levels on the constructor of the Deflater class. Additionally Deflater constructor takes a boolean flag called nowrap, by default Deflater generates a header and ADLER-32 checksum. By setting nowrap to true Deflater will not generate the header or checksum, this make it generate the same bytes as the iOS compressed method.

While the compressed / decompressed methods are available on NSData, unfortunately Apple has not exposed on the swift Data type, so casting to NSData is required.



Decompressing Data

Decompressing the data is similar with the decompressed method on iOS and the Inflater class on Android.




This article has looked at using the Android Inflater / Deflater to generate the same values achieved by iOS's compressed / decompressed methods. This has been achieved by not generating the header and checksum on Android. For some use cases it may be desired to go the opposite way and have iOS generate the header& checksum, for that have a look at