You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.2 KiB

  1. //
  2. // DataRequestExtension.swift
  3. // GMERemittance
  4. //
  5. // Created by gme_2 on 22/08/2018.
  6. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import Foundation
  9. import Alamofire
  10. import ObjectMapper
  11. import SwiftyJSON
  12. enum GMEResponseErrorCode: Int {
  13. case timeOut = 0
  14. case failure
  15. case unknown
  16. case deleted
  17. }
  18. enum GmeResponseOperationStatusCode: String {
  19. case successfull = "Operation Successfull"
  20. }
  21. extension DataRequest {
  22. func handle<T: Mappable>(success: @escaping (T) -> (), failure: @escaping (Error) -> ()) {
  23. self.validate().responseJSON { (response) -> Void in
  24. switch response.result {
  25. case .success(let value):
  26. let json = JSON(value)
  27. if let model: T = json.map() {
  28. success(model)
  29. }else if (response.response?.statusCode ?? -1) == 204 {
  30. let error = self.makeError(message: "Response could not be mapped", code: GMEResponseErrorCode.unknown.rawValue)
  31. // let error = self.makeError(message: "Response could not be mapped", code: GMEResponseErrorCode.unknown.rawValue)
  32. failure(error)
  33. }
  34. else {
  35. // while operation like delete reciepient, api only throws status code 204 with no response. for those case always check errorcode to verify if its is error or it is operation successfull message. The api was desighend this way. I am trying to make our occupation more easier. so while doint operations check if response is only statuscode. is so check the error
  36. let error = self.makeError(message: GmeResponseOperationStatusCode.successfull.rawValue, code: GMEResponseErrorCode.deleted.rawValue)
  37. failure(error)
  38. }
  39. case .failure(let error):
  40. failure(error)
  41. }
  42. }
  43. }
  44. private func makeError(message: String, code: Int) -> Error {
  45. let errorInfo: [String: Any]? = [NSLocalizedDescriptionKey: message]
  46. return NSError.init(domain: "Network", code: code, userInfo: errorInfo)
  47. }
  48. }