Search code examples
jsonswiftcompressiongzipdeflate

gzip compression for API call in Swift


I'm working in Swift with an API that requires you to send JSON compressed using gzip or deflate in the body of your HTTP request. How would I convert testEventModel below into the required compressed JSON format?

struct EventModel: Codable {
    var eventType: String
    var eventName: String?
}

var testEventModel = EventModel(eventType: "TestEvent", eventName: "TestName")

Solution

  • Simplest way, would be to use an existing library for gzipping content, like this one: https://github.com/1024jp/GzipSwift . then your code could look like follows:

    guard let jsonData = try? JSONEncoder().encode(testEventModel),
          let url = URL(string: "https://api.com/endpoint") else {
        return
    }
    let gzipped = jsonData.gzipped()
    
    var request = URLRequest(url: url)
    let postLength = String(format: "%lu", UInt(gzipped.count))
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue(postLength, forHTTPHeaderField: "Content-Length")
    request.addValue("gzip", forHTTPHeaderField: "Content-Encoding")
    request.httpBody = gzipped
    
    URLSession.shared.dataTask(with: request) { data, response, error in
        // handle response
    }.resume()