Last active
September 18, 2024 07:15
-
-
Save kh4zad/5e9e944aa43a8f290b7c865d36387d91 to your computer and use it in GitHub Desktop.
GZIP encoding for Alamofire requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hate to an Oliver Twist, but can you provide sample code for usage. I'm having difficulties in using this.
Thanks