iosjsonswiftalamofire

How to fix invalid JSON issue in pulling data from API using Alamofire in swift?


I need some assistance with my codes. The json below was the original response I got from the postman.

OLD Format

{
   "totalCreditedAmount": 2898.3000,
   "periodId": 566,
   "periodDate": "4/26/2019"
}

So I created the API service code below. It runs smoothly.

APIService

 struct DoctorLatestCreditedAmount {
   typealias getLatestCreditedAmountTaskCompletion = (_ latestCreditedAmount: CurrentRemittance?, _ error: NetworkError?) -> Void

  static func getLatestCreditedAmount(doctorNumber: String, completion: @escaping getLatestCreditedAmountTaskCompletion) {

        guard let latestCreditedAmountURL = URL(string: "\(Endpoint.LatestCreditedAmount.latestCreditedAmount)/\(doctorNumber)") else {
            completion(nil, .invalidURL)
            return
        }

        let sessionManager = Alamofire.SessionManager.default
        sessionManager.session.getAllTasks { (tasks) in
            tasks.forEach({ $0.cancel() })
        }

        Alamofire.request(latestCreditedAmountURL, method: .get, encoding: JSONEncoding.default).responseJSON { (response) in
            guard HelperMethods.reachability(responseResult: response.result) else {
                completion(nil, .noNetwork)
                return
            }

            guard let statusCode = response.response?.statusCode else {
                completion(nil, .noStatusCode)
                return
            }

            switch(statusCode) {
            case 200: guard let jsonData = response.data else {
                completion(nil, .invalidJSON)
                return
                }

                let decoder = JSONDecoder()

            do {
                let currentCreditedAmount = try decoder.decode(CurrentRemittance.self, from: jsonData)
                completion(currentCreditedAmount, nil)
            } catch {
                completion(nil, .invalidJSON)
                }

            case 400: completion(nil, .badRequest)
            case 404: completion(nil, .noRecordFound)
            default:
                print("**UNCAPTURED STATUS CODE FROM (getLatestCreditedAmount)\nSTATUS CODE: \(statusCode)")
                completion(nil, .uncapturedStatusCode)
            }

        }

    }

But when the json side had some changes regarding the response. The json format changed and now using the APIService above I encountered error. It says invalidjson since the new json format is below.

NEW Format

 {
   "responseMessage": "Request successful",
    "data": {
         "totalCreditedAmount": 2898.3000,
         "periodId": 566,
         "periodDate": "4/26/2019"
   }
}

Edited: getTotalCreditedAmount

var currentRemittance: CurrentRemittance!

func getTotalCreditedAmount(doctorNumber: String) {
   windlessSetup()
   APIService.DoctorLatestCreditedAmount.getLatestCreditedAmount(doctorNumber: doctorNumber) { (remittanceDetails, error) in
       guard let creditedAmountDetails = remittanceDetails, error == nil else {
           if let networkError = error {
               switch networkError {
               case .noRecordFound:
                   let alertController = UIAlertController(title: “No Record Found”, message: “You don’t have current payment remittance”, preferredStyle: .alert)
                   alertController.addAction(UIAlertAction(title: “OK”, style: .default))
                    self.present(alertController, animated: true, completion: nil)
               case .noNetwork:
                   let alertController = UIAlertController(title: “No Network”, message: “\(networkError.rawValue)“, preferredStyle: .alert)
                   alertController.addAction(UIAlertAction(title: “OK”, style: .default))
                   self.present(alertController, animated: true, completion: nil)
               default:
                   let alertController = UIAlertController(title: “Error”, message: “There is something went wrong. Please try again”, preferredStyle: .alert)
                   alertController.addAction(UIAlertAction(title: “OK”, style: .default))
                   self.present(alertController, animated: true, completion: nil)
               }
           }
           self.creditedView.windless.end()
           self.remittanceView.windless.end()
           return
       }
       self.currentRemittance = creditedAmountDetails
       self.showLatestTotalCreditedAmount()
       self.creditedView.windless.end()
       self.remittanceView.windless.end()
       return
   }

}

Encountered Error Breakpoint Image

My problem is, how can I alter my codes for APIService so it will match to the proper NEW json format I got. I am having a hard time since I get to used to pulling the same "OLD" format. I am really new to swift and I really need assistance. Hope you can give me some of your time.


Solution

  • Try the code below, it works to me in array of data:

    Alamofire.request(url, method: .get).responseJSON {
    
       response in
    
       if response.result.isSuccess {
    
          let dataJSON = JSON(response.result.value!)
    
           if let datas = dataJSON["data"].arrayObject {
    
             print(datas)
    
          }
    
       }
    
    }