I’m writing an iOS app that wants to read in a zlib compressed data file and uncompress it. This should be easy using the builtin compression library and zlib is one of the supported compression algorithms. Here is my code:
”’
import Compression
do {
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
print("read data of size (fileData.count) bytes")
decompressedData = try (data as NSData).decompressed(using: .zlib) as Data
}
catch {
print("Failed to decompress data: (error)")
}
”’
The decompression keeps failing with Error Domain=NSCocoaErrorDomain Code=5377.
I’ve verified that the file is correctly compressed using zlib compression. I can compress and uncompress the data file on both macos and linux using a python program that uses zlib compression. I can also do the same with zlib-flate. I correctly read the compressed file into a Data object and is 4581383 bytes.
Any suggestions as to why I can’t decompress the data?
Thanks,
Bobby
2
Answers
I used the answer found here: enter link description here suggested by @joachim-isaksson
I removed the first two bytes 0x78 and 0x9c and then zlib decompression started working.
Swift’s "zlib" is raw deflate. You may have zlib-wrapped deflate data. You would need to process the zlib header and trailer yourself (see RFC 1950), and then pass the raw deflate data to Swift’s decompressor.