Search code examples
swiftalamofire

Alamofire with custom parameter encoding for swift application


I have to call some methods from the soap web service in my swift application, so I think I should use custom parameter encoding, but when I create closure for this encoding it seems never to be called. Am I doing something wrong?

Here is my code:

    let custom: (URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?) = {
        (URLRequest, parameters) in
        let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
        mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.HTTPBody = body
        return (mutableURLRequest, nil)
    }

    Alamofire.request(.POST, WebServiceURLString, parameters: nil, encoding: .Custom(custom)).responseString { (request, response, data, error) -> Void in
        println(data)
    }

Solution

  • The custom closure is not executed by design, because there are no parameters to encode. He're a code excerpt taken from Alamofire.swift source file:

    if parameters == nil {
        return (URLRequest.URLRequest, nil)
    }
    

    As you can see, you can bybass this condition by passing an empty dictionary:

    Alamofire.request(.POST, WebServiceURLString, parameters: Dictionary(), encoding: .Custom(custom))
    

    The custom closure will now be executed.