Skip to content

Instantly share code, notes, and snippets.

@kh4zad
Last active September 16, 2021 06:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

@forceunwrap
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