Multiple encoding types for Alamofire Request

2020-08-22 07:44发布

问题:

I need to make a POST request with an HTTP Body with a JSON object, but I also need to use url query parameters in the same request.

POST: http://www.example.com/api/create?param1=value&param2=value
HTTP Body: { foo : [ bar, foo], bar: foo}

Is this supported by Alamofire? How would I go about doing this?

回答1:

This is definitely a valid use case. I've ran into similar issues with trying to append access tokens as query parameters to a POST request. Here's a function that should make things a bit easier for the time being that is similar to your approach.

func multiEncodedURLRequest(
    method: Alamofire.Method,
    URLString: URLStringConvertible,
    URLParameters: [String: AnyObject],
    bodyParameters: [String: AnyObject]) -> NSURLRequest
{
    let tempURLRequest = NSURLRequest(URL: NSURL(string: URLString.URLString)!)
    let URLRequest = ParameterEncoding.URL.encode(tempURLRequest, parameters: URLParameters)
    let bodyRequest = ParameterEncoding.JSON.encode(tempURLRequest, parameters: bodyParameters)

    let compositeRequest = URLRequest.0.mutableCopy() as NSMutableURLRequest
    compositeRequest.HTTPMethod = method.rawValue
    compositeRequest.HTTPBody = bodyRequest.0.HTTPBody

    return compositeRequest
}

With that said, could you make sure to put in a feature request issue on the Github? This is certainly something we need to figure out how to make easier in Alamofire since it's such a common use case. If you could put in a really good description of your use case, then I'm sure it will get attention. I will certainly help press to get support added.



回答2:

At this point, I've decided to solve this by manually encoding an NSURLRequest with the URL parameters, retrieving the URL from that request, and using that to create the final request. I've created a function to return the query parameter encoded request:

private func queryParameterEncodedRequestURL(urlString: String,
values: [String]) -> NSURL {

  let URL = NSURL(string: urlString)
  var request = NSURLRequest(URL: URL)

  let parameters = [
  "param1": values[0]!,
  "param2": values[1]!
  ]

  let encoding = Alamofire.ParameterEncoding.URL
  (request, _) = encoding.encode(request, parameters: parameters)

  return (request.URL, nil)
}

This works fine, but I would definitely like to see Alamofire support multiple encoding types more easily. This feels like a workaround to me.



标签: alamofire