【问题标题】:Alamofire Passing Parameter With Common Keys and Multiple Values?Alamofire 使用公共键和多个值传递参数?
【发布时间】:2017-11-12 13:18:21
【问题描述】:

我需要在我的项目中这样做:

如果我在 Alamofire 中手动将字符串附加到我的 URL,我可以轻松地做到这一点,但我不想那样做。我希望将参数作为 Parameter 对象。

参数的一个公共键中有多个值

我一直在做什么:

public func findCreate(tags: [String], withBlock completion: @escaping FindCreateServiceCallBack) {
    
    /* http://baseurlsample.com/v1/categories/create_multiple?category_name[]=fff&category_name[]=sss */
    
    let findCreateEndpoint = CoreService.Endpoint.FindMultipleCategories
    
    let parameters: Parameters = ["category_name[]" : tags]
    
    Alamofire.request(
        findCreateEndpoint,
        method: .post,
        parameters: parameters,
        encoding: URLEncoding(destination: .queryString),
        headers: nil
        ).responseJSON { (response) in
            print(response)
    }
//....
}

如果我运行它,当前结果还可以,但发送到服务器的值有 [" "]。例如:

["chocolate"]

同样,问题是,我的整个代码的哪一部分错了?如何发送上述具有一个公共键和多个值的参数?

我也尝试将 encoding 选项添加到 Alamofire.request() 如果我添加 encoding: JSONEncoding.prettyPrintedencoding: JSONEncoding.default 我得到 状态码 500。

一些有相同问题但没有确切答案的链接,我总是看到有答案的帖子,比如使用自定义编码,仅此而已。

附加信息:

这可行,但我需要发送多个字符串:

let parameters: [String : Any] = ["category_name[]" : tags.first!]

这也有效:

Alamofire.request("http://baseurlsample.com/v1/categories/create_multiple?category_name[]=fff&category_name[]=sss", method: .post).responseJSON { (data) in
    print(data)
}

【问题讨论】:

    标签: ios swift api alamofire


    【解决方案1】:

    这种格式不需要自定义编码。

    您可以发送这样编码的参数:

    category_name[]=rock&category_name[]=paper
    

    通过使用URLEncoding(您已经在这样做)并在数组中包含应该具有相同键的多个值:

    let parameters: Parameters = ["category_name": ["rock", "paper"]]
    

    它会在category_name 之后为您添加[],因此在声明parameters 时不要包含它。

    【讨论】:

    • 天啊.. 你救了我的一天。这个答案正是我想要的。只需删除参数中的 [] 即可解决我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多