Jochen Österreicher Jochen Österreicher - 15 days ago 9
Swift Question

Alamofire 4, Swift 3 and building a json body

{"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.

Answer

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)
}
Comments