Alamofire 4, Swift 3 and building a json body
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)
}
Jochen Österreicher
Updated on July 28, 2022Comments
-
Jochen Österreicher over 1 year
{"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.
-
Jochen Österreicher over 7 yearsone 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.
-
Nirav D over 7 yearsFor header check this one github.com/Alamofire/Alamofire#http-headers, if you still not get ask new question here.
-
Nirav D over 7 yearsCheck this for passing header stackoverflow.com/a/39512635/6433023