Native zlib inflate / deflate for swift3 on iOS

I would like to be able to inflate / deflate Swift3 Data structs. I found GzipSwift , but it is not clear how I make this available for my iOS application. The naive things I've tried include:

  • Copying the file Data+Gzip.swiftto my own project. He then complains about the import zlibtop of the specified file. I think there is something to do with the modulemap files in the zlib directory from the same sources. But I'm not sure what and how to recreate them in my own project.

  • Cloned the repository from github, opened Xcode and built in (basically hit the start button). Then I tried to add this as a linked library or structure to my own project. I am pretty sure that just selecting the top level directory in the repository is not what I want to do, but I did not know what else to try.

I found another code there, but it seems dated and relative to Swift2.

+4
source share
3 answers

I recently had to add this particular library and file to my project, and after a lot of troubleshooting problems finally worked, let me go through the steps!

Good

1) finder Swiftzlib , , . ( , zlib , Foundation - ). , Swiftzlib , *.xcodeproj *.xcworkspace.

2) .

  • include.h
  • module.modulemap

3) include.h :

#include<zlib.h>

4) module.modulemap :

module Swiftzlib [system] {
    header "include.h"
    export *
}

Swiftzlib .

5) Xcode

  • 5a) → , libz.tbd
  • 5b) → Swift Compiler - , $(PROJECT_DIR)/Swiftzlib
  • 5c) → -lz

6) Xcode (, , , )

  • 6a) → Swift Compiler - , $(PROJECT_DIR)/Swiftzlib

7) Data+Gzip.swfit import Swiftzlib

8) , !

+13

Swift 3+ libcompression Apple:

https://github.com/mw99/DataCompression

gzip:

let data: Data! = "https://www.ietf.org/rfc/rfc1952.txt".data(using: .utf8)
let gzipped: Data! = data.zip()
let gunzipped: Data? = gzipped.unzip()
assert(data == gunzipped)

inflate deflate, .inflate() .deflate(). 18 , gzip .

+2

Implementation of Swift 5 using Compression .

It took me a few days to realize that I had to discard the first 2 bytes of compressed data. Hope this can help someone else.

import Foundation
import Compression

func decompress(_ data: Data) -> String {
    let size = 8_000_000
    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
    let result = data.subdata(in: 2 ..< data.count).withUnsafeBytes ({
        let read = compression_decode_buffer(buffer, size, $0.baseAddress!.bindMemory(to: UInt8.self, capacity: 1),
                                             data.count - 2, nil, COMPRESSION_ZLIB)
        return String(decoding: Data(bytes: buffer, count:read), as: UTF8.self)
    }) as String
    buffer.deallocate()
    return result
}
+1
source

Source: https://habr.com/ru/post/1655533/


All Articles