如何在Swift中使用Alamofire将参数作为主体发送到PUT方法

时间:2018-08-16 12:20:45

标签: swift alamofire put

enter image description here我想将主体中的JSON参数发送到PUT方法,该怎么办?

请在下面找到示例JSON。

func getKOLConnections(emials : [String],phoneNumbers : [String],address : [String],completionHandler: @escaping (Data) -> Void) -> Void {

let url = URl


let parameters :[String: Any]  = ["emails": emials,
                              "phone_numbers" : phoneNumbers,
                              "addresses" : address]

let header : HTTPHeaders =   ["Authorization": "Bearer \("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzQzOTY0MzYsInNlc3Npb25fa2V5IjoiYmZhYjZkZTYtNzlhMy00NDIxLTg2M2YtMTY0MGJlOTQ3NmIzIiwiZXhwIjoxNTM0NDgyODM2fQ.LGclnO9vXxiywoS8TURzcm39pyhNnpeIZ4fzOTvS-jc")",
    "Content-Type": "application/json"] 


 requestdata =  Alamofire.request(url, method: .put, parameters: parameters, encoding: URLEncoding.httpBody, headers: header)
    .validate()
    .responseJSON { (response) in
        switch response.result{
        case .success:
            print(response.data!)

            completionHandler(response.data!)
        case .failure(let error):
            print(error)
        }
 }
 }

2 个答案:

答案 0 :(得分:0)

希望这对您有帮助:

    Alamofire.request(URL(string: "url")!, method: .put, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseJSON { (response) in

        // Handle your response
    }

尝试以下参数:

 let parameters :[String: Any]  = ["emails": [["email" : "", "last_updated_dev" : nil, "is_primary" : nil, "last_updated_by" : nil]],
                                          "phone_numbers" : phoneNumbers,
                                          "addresses" : address]

答案 1 :(得分:0)

该屏幕快照显示您需要传递的参数为:

  • emails
  • phone_numbers
  • addresses

其中emails也是字典,但是,您正在将emials : [String]传递到getKOLConnections。您可以使用以下getKOLConnections签名来修复它:

func getKOLConnections(emails : [String: Any],phoneNumbers : [String],address : [String],completionHandler: @escaping (Data) -> Void) -> Void

我已将emails: [String]更改为emails: [String: Any]

emails: [String:Any]将具有以下键:

  • email
  • last_updated_dev
  • is_primary
  • last_updated_by