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.

Revisions

  1. kh4zad revised this gist Jan 31, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion GZIPEncoding.swift
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    import Alamofire
    import Gzip
    import Gzip // using https://github.com/1024jp/GzipSwift

    public struct GZIPEncoding: ParameterEncoding {

  2. kh4zad created this gist Jan 31, 2018.
    31 changes: 31 additions & 0 deletions GZIPEncoding.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    import Alamofire
    import Gzip

    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
    }
    }