简体   繁体   中英

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?

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM