Jochen Österreicher Jochen Österreicher - 1 year ago 145
Swift Question

Alamofire 4, Swift 3 and building a json body


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! para, options: .init(rawValue: 0))
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as! String

which gives me


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

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.

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.

Answer Source

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

let params = [ 
                "hashTags": [["name":"tag1"],["name":"tag2"]],

Now pass this params as parameter in Alamofire request.

Alamofire.request(postURL, method: .post, parameters: params, encoding: JSONEncoding.default)
    .responseJSON { response in
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download