Created
May 9, 2020 14:41
-
-
Save tadeha/e29bfcaa90239f60bd0732e022ecfb8a to your computer and use it in GitHub Desktop.
An HTTP Client class that handles global requests to our API (GET, POST & PATCH) using Alamofire.
This file contains hidden or 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 Foundation | |
import Alamofire | |
import SwiftyJSON | |
class HTTPClient { | |
static func apiRequestCall(withUrl url: String, method: HTTPMethod, params: [String:Any] = [:], headers: [String:String],encoding: ParameterEncoding = JSONEncoding.default, completion: @escaping (JSON?, Error?) -> Void) { | |
AF.request(url, method: method,parameters: params,encoding: encoding, headers: HTTPHeaders(headers)).validate(statusCode: 200..<600).responseJSON { | |
response in | |
switch response.result { | |
case .success(let value): | |
let json = JSON(value) | |
completion(json, nil) | |
case .failure(let error): | |
completion(nil, error) | |
} | |
} | |
} | |
static func upload(url: String,imageName: String = "avatar",imageData: Data?,progressBar: UIProgressView? = UIProgressView(), params: [String:Any], headers: [String:String],method: HTTPMethod = .patch, completion: @escaping (JSON?, Error?) -> Void) { | |
AF.upload(multipartFormData: { multipartFormData in | |
for (key, value) in params { | |
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String) | |
} | |
if let data = imageData as Data? { | |
multipartFormData.append(data, withName: imageName, fileName: "image.png", mimeType: "image/png") | |
} | |
}, to: url, usingThreshold: UInt64.init(), | |
method: method, | |
headers: HTTPHeaders(headers)) | |
.uploadProgress { progress in | |
if let progressBar = progressBar { | |
progressBar.setProgress(Float(progress.fractionCompleted), animated: true) | |
} | |
} | |
.responseJSON { response in | |
switch response.result { | |
case .success(let json): | |
completion(JSON(json), nil) | |
case .failure(let error): | |
Banner.show(withTitle: "Error in upload: \(error.localizedDescription)", style: .error) | |
completion(nil, error) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment