Skip to content

Instantly share code, notes, and snippets.

@kh4zad
Last active September 18, 2024 07:15
Show Gist options
  • Save kh4zad/5e9e944aa43a8f290b7c865d36387d91 to your computer and use it in GitHub Desktop.
Save kh4zad/5e9e944aa43a8f290b7c865d36387d91 to your computer and use it in GitHub Desktop.
GZIP encoding for Alamofire requests
import Alamofire
import Gzip // using https://github.com/1024jp/GzipSwift
public struct GZIPEncoding: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
guard let parameters = parameters else { return request }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
if request.value(forHTTPHeaderField: "Content-Type") == nil {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
request.httpBody = try data.gzipped()
if request.httpBody != nil {
request.setValue("gzip", forHTTPHeaderField: "Content-Encoding")
}
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return request
}
}
@sunnykaushal81
Copy link

Can you please write code for decoding gzip response

@saschagordner
Copy link

@sunnykaushal81 guess you already know that by now - but Alamofire supports this by default.

@myke91
Copy link

myke91 commented Dec 4, 2020

I hate to an Oliver Twist, but can you provide sample code for usage. I'm having difficulties in using this.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment