如何成功将字符串数组作为参数alamofire传递 [英] How to successfully pass string array as parameter alamofire

查看:588
本文介绍了如何成功将字符串数组作为参数alamofire传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受字符串数组作为参数的终结点,但无法在alamofire中使用它。
我用postman测试了端点,即使在浏览器中也能正常工作,但是使用alamofire时,它将失败并仅返回整个内容(好像我没有输入任何参数)。

I have an endpoint that accepts a string array as parameter but I can't get it working with alamofire. I test my endpoint with postman and it works fine, even in the browser, but with alamofire it fails and just returns the whole thing (as if I didn't put any parameter).

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]时,它的效果很好。

Am I doing something wrong? When I go to url + "?internal_symbols=["4250_XSAU","Test"] on my browser, or postman, it works just fine.

我也尝试设置我的 getQuoteParamaters变量为

I also tried setting my "getQuoteParamaters" variable as

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

但这都不起作用……应该是

but it doesn't work neither... it should be the same thing.

需要澄清的是,该请求在将数组发送到后端时完全忽略了我的参数。

Just to clarify, this request ignores completely my parameters, when it should send the array to my backend.

推荐答案

您只需将字符串数组转换为JSON格式即可。就像下面给出的示例代码一样:

You can simply pass your string array in converting it into a JSON format.Like in the sample code given below:

  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)
    }
  }

这篇关于如何成功将字符串数组作为参数alamofire传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆