1024jp / GzipSwift

Swift package that enables gzip/gunzip Data using zlib
MIT License
544 stars 134 forks source link

Extension for JSONEncoder #42

Closed buh closed 2 years ago

buh commented 5 years ago

Hey!

I want to suggest you to add an extension for JSONEncoder.DataEncodingStrategy that's really help to use GzipSwift for requests:

extension JSONEncoder.DataEncodingStrategy {
    // Gzip data encoding strategy.
    public static var gzip: JSONEncoder.DataEncodingStrategy {
        return .custom { data, encoder throws in
            var container = encoder.singleValueContainer()
            let gzippedData = try data.gzipped()
            try container.encode(gzippedData)
        }
    }
}

Here how it would be easy to use:

let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .gzip
urlRequest.httpBody = try encoder.encode(data)
urlRequest.addValue("gzip", forHTTPHeaderField: "Content-Encoding")

Let me know what you think.