使用URLEncoding为Alamofire post编码Swift数组

时间:2017-07-08 18:43:00

标签: ios swift alamofire

重新发布,因为我之前搞砸了编码类型...... 我需要使用URLEncoding将数组发送到Alamofire服务器。但是,它需要以某种方式编码,以便Alamofire正确发送它。这是我的代码:

xcode-select --install

但是参数永远不会被编码,只是以nil的形式发送。我怎么编码呢?

5 个答案:

答案 0 :(得分:3)

我使用以下自定义编码解决了它:

struct ArrayEncoding: ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try URLEncoding().encode(urlRequest, with: parameters)
        request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
        return request
    }
}

问题是数组的编码方式与foo[]=bar&foo[]=bar2类似,而我的服务器需要它看起来像foo=bar&foo=bar2ArrayEncoding()然后替换请求中的URLEncoding.default

答案 1 :(得分:2)

到目前为止,您可以在参数上使用此问题和问题:

let enc = URLEncoding(arrayEncoding: .noBrackets)
Alamofire.request(url, method: .get, parameters: parameters, encoding: enc)

答案 2 :(得分:0)

试试这段代码,希望它能为您效劳。在此代码中,数组使用NSJSONSerialization进行编码:

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

答案 3 :(得分:0)

这还将影响Twilio的POST正文的多个MediaUrl值。非常感谢您的原始照片,这是POST参数的“正文”版本...

https://gist.github.com/lacyrhoades/4d1e2a4979838901fbe042653714250b

答案 4 :(得分:0)

您可以将 URLEncoding.default 用于 .get httpMethod,而 JSONEncoding.default 用于其他 httpMethod,例如:.post、.delete、.put

AF.request( url,
            method: httpMethod ,
            parameters: parameters,
            encoding: httpMethod == .get ? URLEncoding.default : JSONEncoding.default,
            headers: headers )
    .responseJSON(completionHandler: {})

此外,您可以根据以下代码设置基于 httpMethod 的 httpHeaders 内容类型:

    enum RequestContentType: String {
        case json = "application/json"
        case urlEncoded  = "application/x-www-form-urlencoded"
        case multipart = "multipart/form-data"
    }
                
    let headers :HTTPHeaders  = [ 
                "Content-Type" : httpMethod == .get ? contentType : RequestContentType.json.rawValue 
// add other parameters here ...
            ]