Search code examples
swiftcompressiongzipnsdata

NSData.decompressed throws error in Swift


Hei folks, i want to decompress a gz file using NSData's decompressed method in Swift. The file is loaded successfully into NSData, but if i try to decompress it, it trows error.

var data: NSData
let paths = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)
var url = paths[0]
    
url.appendPathComponent("g.srt.gz")

do {
    data = try Data(contentsOf: url) as NSData
    print(data)
    let dec = try data.decompressed(using: .zlib)
        
} catch { print(error.localizedDescription) }

Here is the output i see:

{length = 17859, bytes = 0x1f8b0800 00000000 00038d7d cd8ee446 ... 10deea38 94b70000 }
The operation couldn’t be completed. (Cocoa error 5377.)

I tried all DecompressionAlgorithms, and i get always the error above. In the Finder i am able to decompress it, so it's not damaged.

Am i missing something (Capability or eomething else in Info.plist) ? I dont want to use any external lib or framework.

My environment is macOS 11.3.1, Xcode 12.5, Swift 5


Solution

  • That data is a gzip stream, not a zlib stream. The method you are using does not have an option for gzip. See this for a solution.