0

I am creating array of dictionaries and then passing that in paramDictionary and sending to server but I get responseStatus code 422. I am using Alamofire 5.

Here is the structure of param which I have to send and it successfully working on postman but in app it is always fails

{"check_in": [{"check_in_at":"2020-02-26 03:23:44", "gps_coordinates":"3.1697998046875,101.61672197976593"}, 
{"check_in_at":"2020-02-26 03:23:45","gps_coordinates":"3.1697998046875,101.61672197976593"}]}

Here is my code

func postCheckInApi(viewController: UIViewController,
                          completion:@escaping (_ result:SuccessErrorData)->(),
                          errorHandler:@escaping (_ result:Error,_ statusCode:Int?)->()//error handler
) {

    let url = KCheckin
    let geoArr = Constant.getSearchLocationHistory() ?? [GeoTaggingEntity]()
    var arr = [[String: String]]()

    for i in geoArr{
        let dict: [String : String] = ["gps_coordinates" : i.gps_coordinates ?? "", "check_in_at" : i.check_in_at]
        arr.append(dict)
    }
    let parameterDictionary = ["check_in": arr] as [String : Any]
    print(parameterDictionary)
    let headers: HTTPHeaders = [
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": Constant.getBearerToken() ?? ""
    ]

    AF.request(url, method: .post, parameters: parameterDictionary, headers: headers).responseData { response in
        switch response.result{
        case.success(let data):
            do{
                let jsonData = try JSONDecoder().decode(SuccessErrorData.self, from: data)
                print("Success")
                completion(jsonData)
            }
            catch{
                //viewController.navigationController?.popToRootViewController(animated: true)
            }
        case .failure(let error):
            print(error)
        }
    }
}
sDev
  • 1,463
  • 9
  • 17
Rahul Gupta
  • 501
  • 1
  • 7
  • 15
  • 1
    i don't see check_in_at key in your dictionary, while adding it to array. Please add that key also – Gyanendra Feb 26 '20 at 06:55
  • can you please show the response of `print(parameterDictionary)` – Manoj Feb 26 '20 at 07:02
  • @Gyanendra here it is "let dict: [String : String] = ["gps_coordinates" : i.gps_coordinates ?? "", "check_in_at" : i.check_in_at]" – Rahul Gupta Feb 26 '20 at 07:07
  • @Manoj. here it is ["check_in": [["gps_coordinates": "3.170011520385742,101.61671682755713", "check_in_at": "2020-02-26 07:02:44"], ["check_in_at": "2020-02-26 07:02:45", "gps_coordinates": "3.170011520385742,101.61671682755713"]]] – Rahul Gupta Feb 26 '20 at 07:07
  • Are you able to do your request in POSTMAN? If so, you can ask POSTMAN to get you a Swift code (bad code, but you can find differences), OR you can use POSTMAN to generate `curl` code that Alamofire can translate too. For curl comparison: https://stackoverflow.com/questions/53637437/alamofire-with-d/53637821#53637821 – Larme Feb 26 '20 at 07:45

1 Answers1

1

You can not add Array as parameter object to your paramDictionary. You need to covert your Array to json string and then add it to you paramDictionary.

For that use below Collection extension to convert your Array to Json String

extension Collection {
    func json() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
            return nil
        }
        return String(data: data, encoding: String.Encoding.utf8)
    }
}

How To Use

let jsonStr = yourArray.json()

add this jsonStr to your paramDictionary

Janbaz Ali
  • 185
  • 1
  • 8
  • let parameterDictionary = ["check_in": arr.json()]// as [String : Any] print(parameterDictionary as Any) ["check_in": Optional("[{\"check_in_at\":\"2020-02-26 13:59:47\",\"gps_coordinates\":\"3.1390933990478516,101.6148388824553\"},{\"gps_coordinates\":\"3.1390933990478516,101.6148388824553\",\"check_in_at\":\"2020-02-26 13:59:47\"}]")] Got Error: The check in must be an array – Rahul Gupta Feb 26 '20 at 14:00