Search code examples
swiftalamofire

How to access Alamofire request parameters inside response closure?


I'm Working on a little project using Swift 2.0 and Alamofire 3. I have few parameters that I need to send to server.

var myParameters = [
            "myObjectName":"FooBar",
            "myObjectId":123456
        ]

To send the data I have a basic request written with Alamofire

let myRequest = Alamofire.request(.POST, MY_SERVICE_URL, parameters: myParameters as! [String : AnyObject], encoding: .JSON)

and I'm getting response like this:

            myRequest.response { myRequest, myResponse, myData, myError in

            /*
            Here I would like to access myParameters, simply to double-check the ID of the data that I have sent out with myRequest.
            */
            print("I'm Done with sending Object number \(myObjectId).")
        }

Is there any simple way to pass myObjectId to response closure? Or access it any other way?


Solution

  • You can retrieve the parameters like this:

    let request = Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON, headers: nil)
    
    request.response { (request, response, data, error) -> Void in
        guard let httpBody = request?.HTTPBody else { return }
        do {
            if let jsonParams = try NSJSONSerialization.JSONObjectWithData(httpBody, options: []) as? [String: AnyObject] {
                if let objectId = jsonParams["myObjectId"] {
                    print(objectId)
                }
            }
        } catch {
            print(error)
        }
    }