响应无法正常工作

时间:2018-04-23 11:26:51

标签: ios swift request httpresponse

这是我使用的代码,我已经传递了像这样的参数和URL

    let headers = [
        "token": "il8uStkZjG3JPefPcjiGIwQ99TGpIL1nmQMyrv0e",
        "Content-Type": "application/json",
      //  "Cache-Control": "no-cache"
        //  "Postman-Token": "97d77826-fcc0-4efd-b01c-e4b1f829e713"
    ]

    let body = ["appointment_time_from": "asdsadasdasdasd"] as [String : Any]

    Alamofire.request(STORE_NEW_ORDER_WITH_PREVIOUS_ADDRESS , method : .post , parameters : body , encoding : URLEncoding.default, headers : headers ).validate().responseSwiftyJSON { (response) in

        switch response.result {

        case .success:
            let data = response.value
            print(data ?? "" )

            print("Validation Successful")

        case .failure(let error):
            print(error)
        }

    }

输出:

{
  "obj" : [

  ]
}
  

注意:它在Postman中完美运作:

3 个答案:

答案 0 :(得分:1)

我不确定您收到回复的格式:

通常它的工作原理如下:

假设答案在[String:Any]

let urlString = "https://httpbin.org/get"

Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON {  
response in
  switch response.result {
                case .success:
                    let dataResponse = response.result.value as! [String:Any]
                    print(dataResponse)

                    break
                case .failure(let error):

                    print(error)
                }
}

答案 1 :(得分:0)

使用像这样: -

let headers = [
    "token": "il8uStkZjG3JPefPcjiGIwQ99TGpIL1nmQMyrv0e",
    "Content-Type": "application/json",
  //  "Cache-Control": "no-cache"
    //  "Postman-Token": "97d77826-fcc0-4efd-b01c-e4b1f829e713"
]

let body = ["appointment_time_from": "asdsadasdasdasd"] as [String : Any]

Alamofire.request(STORE_NEW_ORDER_WITH_PREVIOUS_ADDRESS , method : .post , parameters : body , encoding : URLEncoding.default, headers : headers ).validate().responseSwiftyJSON { (response) in

    switch response.result {

    case .success:
        if let data = response.result.value as? [String: AnyObject] {
          if let objectArray = data["obj"] as? NSArray {
          }
         }
    case .failure(let error):
        print(error)
    }

}

如果它不起作用,请尝试将编码类型更改为JSONEncoding.default

还可以尝试删除编码参数

答案 2 :(得分:0)

使用此代码。希望对您有所帮助

func GetDataAPI()
{
    let url = "your URL"
    var param : [String : AnyObject] = [:]

    param = ["appointment_time_from": "asdsadasdasdasd" as AnyObject]
    print(param)
    Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
        print(response)

        if (response.result.value != nil)
        {
            //your code
        }
        else
        {
            //your code
        }
    }
}