简体   繁体   English

如何在响应闭包内部访问Alamofire请求参数?

[英]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. 我正在使用Swift 2.0和Alamofire 3进行一个小项目。我需要发送给服务器的参数很少。

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

To send the data I have a basic request written with Alamofire 要发送数据,我有一个用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? 有什么简单的方法可以将myObjectId传递给响应闭包? 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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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