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

时间:2015-10-23 17:06:57

标签: swift alamofire

我正在使用Swift 2.0和Alamofire 3开展一个小项目。 我有几个参数需要发送到服务器。

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

要发送数据,我有一个用Alamofire写的基本请求

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

我收到这样的回复:

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

有没有简单的方法将myObjectId传递给响应闭包?或者以其他方式访问它?

1 个答案:

答案 0 :(得分:1)

您可以检索如下参数:

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