加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Alamofire 4,Swift 3和构建json身体

发布时间:2020-12-14 04:58:45 所属栏目:百科 来源:网络整理
导读:{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":[{"fileBytes":"seriesOfBytesn","filename":"upload.txt"}]} 这是我想要发送到后端的我想要的身体. 我正在使用Swift 3.0和Alamofire 4,我有很多问题. 首先,我如何正
{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":
[{"fileBytes":"seriesOfBytesn","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":"seriesOfBytesn","filename":"upload.txt"]]
             ]

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读