使用URLEncoding对Swift数组进行编码以进行Alamofire POST请求

6

由于之前编码类型出错,现在重新发布... 我需要使用URLEncoding将一个数组发送到服务器,但是为了让Alamofire正确地发送它,它需要以某种方式进行编码。这是我的代码:

let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }

然而,参数从未被编码,只是被发送为nil。我该如何进行编码?
5个回答

7

目前,您可以在参数上使用以下内容来解决此问题:

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

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=bar2。因此,在请求中,ArrayEncoding() 替换了URLEncoding.default

您可以使用Rômulo Diniz的建议来改进您的答案。不再需要进行字符串替换! - Pim

0

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

我之前从另一个Stackoverflow帖子尝试过这段代码,但它没有起作用。我认为这是因为它在请求正文中设置了值,但我想要将其编码在URL中,例如?names=bob&names=fred。 - Tometoyou
我认为编码不是问题,肯定还有其他问题。或者问题可能来自服务器端。 - Zohaib Hassan

0

你可以在使用 .get httpMethod 时使用 URLEncoding.default,在使用其他 httpMethods(例如:.post、.delete、.put)时使用 JSONEncoding.default。

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

此外,您可以根据以下代码设置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 ...
            ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接