How to send POST request with both parameter and body for JSON data in Swift 3 using Alamofire 4?
You are mixing two things here, page
,size
and sortBy
is you need to pass with the url string as query string. Now your body is request is JSON
Array and you can post array with Alamofire
only using URLRequest
. So try like this.
let baseUrl = "abc.com/search/"let queryStringParam = [ "page":"1", "size":"5", "sortBy":"profile_locality"]//Make first url from this queryStringParam using URLComponentsvar urlComponent = URLComponents(string: baseUrl)!let queryItems = queryStringParam.map { URLQueryItem(name: $0.key, value: $0.value) }urlComponent.queryItems = queryItems//Now make `URLRequest` and set body and headers with itlet param = [ [ "fieldName" : "abc", "fieldValue":"xyz" ], [ "fieldName" : "123", "fieldValue":"789" ]]let headers = [ "Content-Type": "application/json" ]var request = URLRequest(url: urlComponent.url!)request.httpMethod = "POST"request.httpBody = try? JSONSerialization.data(withJSONObject: param)request.allHTTPHeaderFields = headers//Now use this URLRequest with Alamofire to make requestAlamofire.request(request).responseJSON { response in //Your code}
Try this: Using Custom Encoding
struct JSONStringArrayEncoding: ParameterEncoding { private let array: [[String : Any]] init(array: [[String : Any]]) { self.array = array } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() let data = try JSONSerialization.data(withJSONObject: array, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return urlRequest }}
Calling
let values = [ [ "fieldName" : "abc", "fieldValue":"xyz" ], [ "fieldName" : "123", "fieldValue":"789" ] ] let param = [ "page":"1", "size":"5", "sortBy":"profile_locality" ] let parameterEncoding = JSONStringArrayEncoding.init(array: values) Alamofire.request("url", method: .post, parameters: param, encoding:parameterEncoding ).validate().response { (responseObject) in // do your work }