Alfonso Alfonso - 1 year ago 69
iOS Question

Print Alamofire request body

I'm using Alamofire library for connecting with an API in iOs. I have a problem in one of the connection, and I don't know if it is because of the data encoded in the body or any other thing. In order to detect my error, I'm trying to print in the console the request body for checking if I'm sending the correct data structure.

My code is the following:

func updateUser (#user: User, completionHandler: (responseObject: User?, error: AnyObject?) -> ()) {
let parameters = [
"_id": "\(user._id!)",
"email": "\(!)",
"media": "\(Mapper().toJSONArray(!))",
"blogs": "\(Mapper().toJSONArray(user.blogs!))"

var manager = Alamofire.Manager.sharedInstance
manager.request(.PUT, apiUrl + "/route/to/api", parameters: parameters, encoding: .JSON)
.responseObject{ (req: NSURLRequest, res: NSHTTPURLResponse?, user: User?, data: AnyObject?, error: NSError?) in
if(error != nil) {
NSLog("Error API updateUser: \(error)")
else {
completionHandler(responseObject: user as User?, error: data)

User is a Mappable object, since I'm using ObjectMapper combined with Alamofire. User is defined by the following code:

class User: Mappable {
var _id: String?
var name: String?
var media: [Media]?

init(_id: String, name: String, media: [Media]){
self._id = _id; = name; = media

required init=(_ map: Map){

func mapping(map: Map){
_id <- map["_id"]
name <- map["name"]
media <- map["media"]

Media is defined like User, but with different variables.

Also, I would like to know, in addition of printing request body, if I could include the parameters to Alimofire request in a more efficient way (something like parsing the User object and substituting it for the parameters variable)

Any idea about my problems?


Following the suggestion of @Travis, finally I found the solution for printing the request body. Below you could find the code:

println("request body: \(NSString(data:req.HTTPBody!, encoding:NSUTF8StringEncoding) as String?)")

About passing as parameters an object I couldn't work it, I followed the official documentation, but I could do it.

Answer Source

The answer to your first question is,

println("request body: \(request.HTTPBody)")

As far as your 2nd question goes, there's a whole section on API Parameter Abstraction as well as CRUD & Authorization on the Alamofire main page.