Skip to content

Instantly share code, notes, and snippets.

@takasurazeem
Last active January 15, 2022 19:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takasurazeem/20d49a0b15db25dc959c74fe696d0f6a to your computer and use it in GitHub Desktop.
Save takasurazeem/20d49a0b15db25dc959c74fe696d0f6a to your computer and use it in GitHub Desktop.
Alamofire Wrapper
//
// SCService.swift
//
// Created by Takasur Azeem on 09/03/2021.
//
import Alamofire
/// `SCRequest` is just a name, `SC` is the project name initials, I could use `TA` as well. You can name them anything.
/// As long as what you pass as `SCRequest` conforms to `Encodable` and what you pass as `SCResponse` conforms to `Codable`
struct SCService<SCRequest, SCResponse> where SCRequest: Encodable, SCResponse: Codable {
/// This function accepts SCRequest as parameters and completes result in closure as SCResponse
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
/// `JSONParameterEncoder()` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `["Content-Type" : "application/json"]` by default.
/// - completion: a closure that captures `AFResult` enum.
/// - result: captures `AFResult<SCResponse>`
func request(_ convertible: URLConvertible,
method: HTTPMethod = .post,
parameters: SCRequest? = nil,
encoder: ParameterEncoder = JSONParameterEncoder(),
header: [String:String] = ["Content-Type" : "application/json"],
completion: @escaping (_ result: AFResult<SCResponse>) -> Void) {
// let httpHeader = HTTPHeaders(header)
// debugPrint("Header: \(httpHeader)")
// if let parameters = parameters {
// debugPrint("Parameters: \(parameters)")
// }
AF.request(convertible, method: method, parameters: parameters, encoder: encoder, headers: httpHeader).responseDecodable { (response) in
completion(response.result)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment