Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending json array via Alamofire

I wonder if it's possible to directly send an array (not wrapped in a dictionary) in a POST request. Apparently the parameters parameter should get a map of: [String: AnyObject]? But I want to be able to send the following example json:

[     "06786984572365",     "06644857247565",     "06649998782227" ] 
like image 597
fruechtemuesli Avatar asked Nov 19 '14 21:11

fruechtemuesli


1 Answers

You can just encode the JSON with NSJSONSerialization and then build the NSURLRequest yourself. For example, in Swift 3:

var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type")  let values = ["06786984572365", "06644857247565", "06649998782227"]  request.httpBody = try! JSONSerialization.data(withJSONObject: values)  AF.request(request)                               // Or `Alamofire.request(request)` in prior versions of Alamofire     .responseJSON { response in         switch response.result {         case .failure(let error):             print(error)                          if let data = response.data, let responseString = String(data: data, encoding: .utf8) {                 print(responseString)             }         case .success(let responseObject):             print(responseObject)         } } 

For Swift 2, see previous revision of this answer.

like image 199
Rob Avatar answered Sep 20 '22 00:09

Rob