POST request with a simple string in body with Alamofire POST request with a simple string in body with Alamofire ios ios

POST request with a simple string in body with Alamofire


Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body.But if you really want string with custom format. You can do this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({            (convertible, params) in            var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest            mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)            return (mutableRequest, nil)        }))

Note: parameters should not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.

extension String: ParameterEncoding {    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {        var request = try urlRequest.asURLRequest()        request.httpBody = data(using: .utf8, allowLossyConversion: false)        return request    }}Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])


You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)request.httpMethod = HTTPMethod.post.rawValuerequest.setValue("application/json", forHTTPHeaderField: "Content-Type")let pjson = attendences.toJSONString(prettyPrint: false)let data = (pjson?.data(using: .utf8))! as Datarequest.httpBody = dataAlamofire.request(request).responseJSON { (response) in    print(response)}


If you use Alamofire, it is enough to set encoding type to URLEncoding.httpBody

With that, you can send your data as a string in the httpbody although you defined it as json in your code.

It worked for me..

Updated for Badr Filali's question:

var url = "http://..."let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]let url =  NSURL(string:"url" as String)request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: _headers).responseJSON(    completionHandler: { response in response        let jsonResponse = response.result.value as! NSDictionary                if jsonResponse["access_token"] != nil        {            access_token = String(describing: jsonResponse["accesstoken"]!)        }    })