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.