Last active
September 13, 2018 04:57
-
-
Save balitax/feae361311ace824f691341aa3244394 to your computer and use it in GitHub Desktop.
APIManager.swift
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
// | |
// ApiManager.swift | |
// DOTAPI | |
// | |
// Created by Agus Cahyono on 16/04/18. | |
// Copyright © 2018 Agus Cahyono. All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
struct APIManager { | |
static var manager: SessionManager! | |
/// GET FROM API | |
/// | |
/// - Parameters: | |
/// - url: URL API | |
/// - method: methods | |
/// - parameters: parameters | |
/// - encoding: encoding | |
/// - headers: headers | |
/// - completion: completion | |
/// - failure: failure | |
static func request(_ url: String, method: HTTPMethod, parameters: Parameters, encoding: ParameterEncoding, headers: HTTPHeaders, completion: @escaping (_ response: Data) ->(), failure: @escaping (_ error: String, _ errorCode: Int) -> ()) { | |
let configuration = URLSessionConfiguration.default | |
configuration.timeoutIntervalForRequest = 30 | |
configuration.timeoutIntervalForResource = 30 | |
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders | |
manager = Alamofire.SessionManager(configuration: configuration) | |
let apiURL = "baseURL" + url | |
print("-- URL API: \(apiURL), \n\n-- headers: \(headers), \n\n-- Parameters: \(parameters)") | |
manager.request( | |
apiURL, | |
method: method, | |
parameters: parameters, | |
encoding: encoding, | |
headers: headers).responseString( | |
queue: DispatchQueue.main, | |
encoding: String.Encoding.utf8) { response in | |
print("--\n \n CALLBACK RESPONSE: \(response)") | |
if response.response?.statusCode == 200 { | |
guard let callback = response.data else { | |
failure(self.generateRandomError(), 0) | |
return | |
} | |
completion(callback) | |
} else if response.response?.statusCode == 401 { | |
// add function automatically logout app | |
} else { | |
guard let callbackError = response.data else { | |
return | |
} | |
do { | |
let decoded = try JSONDecoder().decode( | |
APIError.self, from: callbackError) | |
if let messageError = decoded.data?.errors?.messages, let errorCode = decoded.statusCode { | |
let messages = messageError.joined(separator: ", ") | |
failure(messages, errorCode) | |
} else { | |
failure(APIManager.generateRandomError(), 0) | |
} | |
} catch _ { | |
failure(APIManager.generateRandomError(), 0) | |
} | |
} | |
} | |
} | |
/// GENERATE RANDOM ERROR | |
/// | |
/// - Returns: string error randoms | |
static func generateRandomError() -> String { | |
return "Oops. There is an error. Please reload." | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment