Alamofire 4,Swift 3和构建json主体

编程入门 行业动态 更新时间:2024-10-28 20:26:09
本文介绍了Alamofire 4,Swift 3和构建json主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 {"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.

我正在使用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主体

本文发布于:2023-11-26 06:14:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主体   Alamofire   Swift   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!