如何在我的iOS应用程序中使用Alamofire在HTTP正文中发送带有简单字符串的POST请求?
默认情况下,Alamofire需要请求的参数:
Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
Run Code Online (Sandbox Code Playgroud)
这些参数包含键值对.但我不想在HTTP正文中发送带有键值字符串的请求.
我的意思是这样的:
Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString")
Run Code Online (Sandbox Code Playgroud) {"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":
[{"fileBytes":"seriesOfBytes\n","filename":"upload.txt"}]}
Run Code Online (Sandbox Code Playgroud)
这是我想要发送到后端的我想要的身体.
我正在使用Swift 3.0和Alamofire 4,我有很多问题.
首先,我如何正确创建包含值和值数组的主体?
我的方法是:
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)
Run Code Online (Sandbox Code Playgroud)
这给了我
{"title":"exampleTitle"}
Run Code Online (Sandbox Code Playgroud)
第二,我的alamofire .post请求如下所示,并且不起作用:
Alamofire.request(postURL, method: .post, parameters: jsonString, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response)
}
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:调用中的额外参数'方法'.如果我而不是jsonString使用该类型的字符串
var jsonString: [String : Any]
Run Code Online (Sandbox Code Playgroud)
它确实有效,但我不知道如何将身体放入这种类型.
总结 寻找帮助(例如将是最好的)如何创建身体,以及如何通过Alamofire 4和swift 3发送到我的后端.