Alamofire 4,Swift 3和构建json主体 [英] Alamofire 4, Swift 3 and building a json body

查看:90
本文介绍了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主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆