这是我想要发送到后端的所需正文.
That is my desired body I want to send to the backend.
我正在使用Swift 3.0和Alamofire 4,并且我有多个问题.
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?
我的方法是:
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)这给了我
{"title":"exampleTitle"}秒,我的alamofire .post请求如下所示,但不起作用:
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) }我收到错误消息:调用中有额外的参数"method".如果我而不是jsonString,请使用类型
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.
摘要 寻找有关如何创建身体以及如何通过Alamofire 4和swift 3将其发送到我的后端的帮助(最好的例子).
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.
推荐答案您需要将参数作为[String:Any]字典传递,因此像这样传递JSON来创建一个字典.
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"]] ]现在将此params作为参数传递给Alamofire请求.
Now pass this params as parameter in Alamofire request.
Alamofire.request(postURL, method: .post, parameters: params, encoding: JSONEncoding.default) .responseJSON { response in debugPrint(response) }更多推荐
Alamofire 4,Swift 3和构建json主体
发布评论