Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created February 25, 2019 11:05
Show Gist options
  • Save JarvisTheAvenger/9121885f932bb2eead82ebf8abe405e6 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/9121885f932bb2eead82ebf8abe405e6 to your computer and use it in GitHub Desktop.
import Alamofire
import SwiftyJSON
class APIManager {
private init(){}
class func request(
_ url: URLConvertible,
method: HTTPMethod,
parameters: Parameters?,
completionHandler: @escaping (JSON) -> Void)
{
var parameters = parameters
if method == .get {
parameters = nil
}
let parameterEncoding: ParameterEncoding = JSONEncoding.default
var httpHeaders: HTTPHeaders = HTTPHeaders()
httpHeaders["Content-Type"] = "application/json"
Alamofire
.request(url,
method : method,
parameters : parameters,
encoding : parameterEncoding,
headers : httpHeaders)
.responseJSON(completionHandler: { (response) in
func handleSuccess(_ responseJSON: Any) {
let json = JSON(responseJSON)
completionHandler(json)
}
func handleNetworkError(_ error: Error) {
let alertController = UIAlertController(title: "Network Error",
message: error.localizedDescription,
preferredStyle: .alert)
let btnRetry = UIAlertAction(title: "Retry",
style: .default,
handler: { (action) in
request(url,
method: method,
parameters: parameters,
completionHandler: completionHandler)
})
alertController.addAction(btnRetry)
let btnCancel = UIAlertAction(title: "Cancel",
style: .cancel,
handler: { (action) in
let customError: [String: Any] = ["success": false,
"error_id": error._code,
"message": error.localizedDescription]
let json = JSON(customError)
completionHandler(json)
})
alertController.addAction(btnCancel)
let vc = APIManager.getTopMostViewController()
if !(vc is UIAlertController) {
vc?.present(alertController,
animated: true,
completion: nil)
}
}
switch(response.result) {
case .success(let responseJSON):
handleSuccess(responseJSON)
case .failure(let error):
//Network related error
handleNetworkError(error)
}
})
}
class func getTopMostViewController() -> UIViewController? {
var topMostViewController = UIApplication.shared.keyWindow?.rootViewController
while let presentedViewController = topMostViewController?.presentedViewController {
topMostViewController = presentedViewController
}
return topMostViewController
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment