Last active
January 15, 2022 19:33
-
-
Save takasurazeem/20d49a0b15db25dc959c74fe696d0f6a to your computer and use it in GitHub Desktop.
Alamofire Wrapper
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
// | |
// 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