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.

Swift

Kotlin


Decompressing Data

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

Swift

Kotlin

Conclusion

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 https://github.com/mw99/DataCompression.

2 comments:

  1. Thanks for sharing this information KSAC is one of the most trusted multi-specialty Ayurvedic hospitals in India. For over two decades, we provides 100% Evidence based Treatments for diseases, Naturally.Best Ayurveda Hospital in Hyderabad, Bengalore, India

    ReplyDelete
  2. Its very informative blog and useful article thank you for sharing with us , keep posting learn
    msbi online course | msbi online training

    ReplyDelete