Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple encoding types for Alamofire Request

Tags:

alamofire

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?

like image 303
AnthonyMDev Avatar asked Mar 06 '15 22:03

AnthonyMDev


1 Answers

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.

like image 160
cnoon Avatar answered Oct 26 '22 00:10

cnoon