微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Alamofire 4,Swift 3和构建json身体

{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":
[{"fileBytes":"seriesOfBytes\n","filename":"upload.txt"}]}

这是我想要发送到后端的我想要的身体.

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

这给了我

{"title":"exampleTitle"}

第二,我的alamofire .post请求如下所示,并且不起作用:

Alamofire.request(postURL,method: .post,parameters: jsonString,encoding: JSONEncoding.default)
        .responseJSON { response in
            debugPrint(response)
    }

我收到错误消息:调用中的额外参数’方法’.如果我而不是jsonString使用该类型的字符串

var jsonString: [String : Any]

它确实有效,但我不知道如何将身体放入这种类型.

摘要
寻找帮助(例如最好的)如何创建身体,以及如何通过Alamofire 4和swift 3将其发送到我的后端.

解决方法

您需要将参数作为[String:Any]字典传递,因此创建一个字典作为您传递的JSON.

let params = [ 
                "title":"exampleTitle","hashTags": [["name":"tag1"],["name":"tag2"]],"uploadFiles":[["fileBytes":"seriesOfBytes\n","filename":"upload.txt"]]
             ]

现在将此参数作为参数传递给Alamofire请求.

Alamofire.request(postURL,parameters: params,encoding: JSONEncoding.default)
    .responseJSON { response in
        debugPrint(response)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐