8
{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":
[{"fileBytes":"seriesOfBytes\n","filename":"upload.txt"}]}

That is my desired body I want to send to the backend.

I'm using Swift 3.0 and Alamofire 4 and i have multiple questions.

first, How do i correctly create a body which contains values and arrays of values?

My approach is:

let para:NSMutableDictionary = NSMutableDictionary()
para.setValue("exampleTitle", forKey: "title")
let jsonData = try! JSONSerialization.data(withJSONObject: para, options: .init(rawValue: 0))
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as! String
print(jsonString)

which gives me

{"title":"exampleTitle"}

second, my alamofire .post request looks like the following and is not working:

Alamofire.request(postURL, method: .post, parameters: jsonString, encoding: JSONEncoding.default)
        .responseJSON { response in
            debugPrint(response)
    }

i get the error message: extra argument 'method' in call. If i instead of jsonString use a string of the type

 var jsonString: [String : Any]

it does work, but i do not know how to put the body into this type.

summary looking for help (example would be the best) on how to create the body, and how to send it via Alamofire 4 and swift 3 to my backend.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Jochen Österreicher
  • 683
  • 2
  • 11
  • 25
  • Possible duplicate of [How to send a POST request with BODY in swift](http://stackoverflow.com/questions/31982513/how-to-send-a-post-request-with-body-in-swift) – haider_kazal Nov 20 '16 at 11:38

1 Answers1

21

You need to pass parameter as [String:Any] dictionary, so create one dictionary as your passing JSON like this.

let params = [ 
                "title":"exampleTitle",
                "hashTags": [["name":"tag1"],["name":"tag2"]],
                "uploadFiles":[["fileBytes":"seriesOfBytes\n","filename":"upload.txt"]]
             ]

Now pass this params as parameter in Alamofire request.

Alamofire.request(postURL, method: .post, parameters: params, encoding: JSONEncoding.default)
    .responseJSON { response in
        debugPrint(response)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • one more question before i mark it as accepted: i have headers too, where do i place them in the request and how do they need to be formatted? i tried to add them like parameters but it gave me the extra call message again. – Jochen Österreicher Nov 20 '16 at 10:56
  • For header check this one https://github.com/Alamofire/Alamofire#http-headers, if you still not get ask new question here. – Nirav D Nov 20 '16 at 11:09
  • Check this for passing header http://stackoverflow.com/a/39512635/6433023 – Nirav D Nov 20 '16 at 11:15