1

Similar questions to this have been posted before but with slight differences, namely:

Alamofire: Sending JSON as request parameter

POST multiple json objects in Alamofire POST method - Swift/IOS

Sending json array via Alamofire

being the last one, the closest to my current problem. However, this solution is not working for me.

The problem I am facing is that I'm trying to send through an Alamofire POST request, a JSON that I've built using SwiftyJSON. Like so:

let url = NSURL(string: orderProductsEndpoint)
                let request = NSMutableURLRequest(URL: url!)
                request.HTTPMethod = "POST"
                request.setValue(requestToken, forHTTPHeaderField: "Authorization:")
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")

                let params = [ json.object ]
                print(params)

                request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject( params, options: [])


                Alamofire.request(request)
                    .responseString{ response in
                        switch response.result {
                        case .Success(let value):
                            print("gut")
                            print(value)
                        case .Failure(let error):
                            print("not gut")
                            print(error)
                        }
                }

However, this is not working well because the API that I'm communicating with doesn't seem to recognize well the parameters that I'm sending.

But then I noticed that what I am sending is not a valid JSON. This is what I am sending:

  [{
car =     (
            {
        cant = 2;
        id = 6;
        name = "Saudi Plate";
    },
            {
        cant = 1;
        id = 5;
        name = "Beef Wrap";
    }
);
idUser = 58;
"total_loyalty_points" = 4200;
"total_price" = 42000;}]

But before converting my JSON to an object using

let params = [ json.object ]

It was a valid JSON validated through JSONLint and it looks like this

{
  "total_price" : 42000,
  "car" : [
    {
      "id" : "6",
      "cant" : 2,
      "name" : "Saudi Plate"
    },
    {
      "id" : "5",
      "cant" : 1,
      "name" : "Beef Wrap"
    }
  ],
  "idUser" : 58,
  "total_loyalty_points" : 4200
}

So the problem is that I was forced to change the structure of the JSON because it seems to be the only way to send it through Alamofire, by converting it into an object. Is there a way to actually send raw JSON through Alamofire?

Community
  • 1
  • 1
Jesus Rodriguez
  • 2,571
  • 2
  • 22
  • 38

2 Answers2

1

Try to get your params as Alamofire parameters i.e [String : Any].

Basically you want to send raw json with post method.

Below function will do a post request with raw json. Also this is with generics

func nwCallRawJSon<T: Decodable>(url : String, param : [String : Any],decodable: T.Type,onCompletion: @escaping (T?,Error?) -> Void){
        AF.request(url, method: .post, parameters : param, encoding: JSONEncoding.default, headers: nil).validate(contentType: ["application/json"]).responseDecodable { (response: DataResponse<T,AFError>) in
            switch response.result {
            case .success(let data):
                onCompletion(data,nil)
            case .failure(let error):
                onCompletion(nil,error)
            }
        }
    }
Bilal Khan
  • 1,023
  • 7
  • 9
0

Try setting the json encoding for your parameters in the Alamofire request.

Alamofire.request("http://...", method: HTTPMethod.post, parameters: parameters, encoding: JSONEncoding.default, headers: nil)
         .responseJSON(completionHandler: {(response) in ... })

https://github.com/Alamofire/Alamofire#json-encoding

Derek Soike
  • 11,238
  • 3
  • 79
  • 74