问题
I have some data that has been compressed with the DEFLATE algorithm which I believe is basically just saying its zipped up. I'm writing a swift app and I was interested in figuring out if there is a native pure swift (2.0) implementation of the unzip algorithm.
I need to implement this in a swift dynamic framework, and as such it would be preferable if i didn't have to use Objective-c code as that requires me to make an objc framework included by my swift framework etc.
I guess my question is either is there a native swift implementation or is there a way to use swift to call into zlib to do the unzipping natively?
Thanks
回答1:
There is a native swift implementation of zlib on github called DeflateSwift
回答2:
Take a look at the Compression framework introduced by Apple this summer.
I believe it can decompress any ZLIB compressed file (among other things) and should be pretty efficient at that.
回答3:
Clean Swift 3 wrapper around Apples new libcompression: https://github.com/mw99/SwiftDataCompression
Usage example:
let s = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ_0123456789"
var res: Data? = s.data(using: .utf8)
res = res?.deflate()
res = res?.inflate()
res = res?.zip()
res = res?.unzip()
res = res?.compress(withAlgorithm: .LZFSE)
res = res?.decompress(withAlgorithm: .LZFSE)
res = res?.compress(withAlgorithm: .LZ4)
res = res?.decompress(withAlgorithm: .LZ4)
res = res?.compress(withAlgorithm: .LZMA)
res = res?.decompress(withAlgorithm: .LZMA)
res = res?.compress(withAlgorithm: .ZLIB)
res = res?.decompress(withAlgorithm: .ZLIB)
assert(res != nil)
let t = String(data: res!, encoding: .utf8)
assert(s == t)
Trying this in the playground is quite interesting because by changing the input string you can see immediately see the compression ratio.
回答4:
"zipped up" implies the .zip format, which is not the same as saying it has been compressed with deflate. The .zip format is an archive wrapper around compressed data formats that permits the compression and storage of files and directory structures, along with attributes, in a single .zip file. The compressed data formats include deflate (which is the most commmon).
So your deflate compressed data is likely not wrapped in the .zip file format.
Deflate compressed data can be found wrapped in gzip (.gz) files, PDF files, PNG files, and other formats.
In any case, you can use zlib to decompress the raw deflate format, however it may be wrapped, or not, in your data. zlib is already present in OS X and iOS as a shared library. As noted by @MirekE, you can access it from the new Compression Framework.
来源:https://stackoverflow.com/questions/31953852/native-swift-implementation-of-deflate-unzip-algorithm