Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request with a simple string in body with Alamofire

how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?

As default Alamofire needs parameters for a request:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) 

These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.

I mean something like this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString") 
like image 378
Karl Avatar asked Jan 09 '15 06:01

Karl


People also ask

What is Alamofire?

Alamofire is a Swift-based, HTTP networking library. It provides an elegant interface on top of Apple's Foundation networking stack that simplifies common networking tasks. Its features include chainable request/response methods, JSON and Codable decoding, authentication and more.


1 Answers

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: [:]) 
like image 112
Silmaril Avatar answered Sep 17 '22 13:09

Silmaril