如何成功传递字符串数组作为参数alamofire

时间:2017-05-08 19:17:30

标签: ios swift swift3 httprequest alamofire

我有一个接受字符串数组作为参数的端点,但我无法使用alamofire。 我用postman测试我的端点并且它工作正常,即使在浏览器中,但是使用alamofire它失败并且只返回整个事物(好像我没有放任何参数)。

func getQuotes(String url){

    //THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX

    let stringArray : [String] = ["4250_XSAU", "Test"]
    let getQuoteParameters : Parameters = [
        //"internal_symbols": stockInternalSymbols
        "internal_symbols" : stringArray
    ]

    print("attempting to get quotes on utility queue")

    Alamofire.request(url, parameters: getQuoteParameters).responseJSON{ response in
        print(response)

       /* if (response.result.value != nil){
            let jsonResponse = JSON(response.result.value!)

           print(jsonResponse) 
        }
       */
    }
}

我做错了吗?当我在我的浏览器或邮递员上访问url +"?internal_symbols = [" 4250_XSAU"," Test"]时,它运行正常。

我也试过设置我的" getQuoteParamaters"变量为

let getQuoteParameters : Parameters = [
        "internal_symbols" : ["4250_XSAU", "Test"]
    ]

但它既不起作用......也应该是一样的。

只是澄清一下,这个请求完全忽略了我的参数,它应该将数组发送到我的后端。

3 个答案:

答案 0 :(得分:2)

您可以简单地传递字符串数组,将其转换为JSON格式。如下面的示例代码所示:

  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")

  let values = ["06786984572365", "06644857247565", "06649998782227"]

  request.httpBody = try! JSONSerialization.data(withJSONObject: values)

 Alamofire.request(request)
.responseJSON { response in
    // do whatever you want here
    switch response.result {
    case .failure(let error):
        print(error)

        if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
            print(responseString)
        }
    case .success(let responseObject):
        print(responseObject)
    }
  }

答案 1 :(得分:0)

请在您的请求中添加编码标准,例如JSONEncoding.default

func getQuotes(String url){

//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX

let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
    //"internal_symbols": stockInternalSymbols
    "internal_symbols" : stringArray
]

print("attempting to get quotes on utility queue")

Alamofire.request(url, method: .post, parameters: getQuoteParameters, encoding: JSONEncoding.default).responseJSON{ response in
    print(response)

   /* if (response.result.value != nil){
        let jsonResponse = JSON(response.result.value!)

       print(jsonResponse) 
    }
   */
}

感谢。

答案 2 :(得分:0)

我在Swift 3的解决方案:

let text: [String] = ["location.branches.longitude", "location.branches.latitude"]

let params: Parameters = [
  "_source": text
]