gpt4 book ai didi

swift - 如何在响应闭包中访问 Alamofire 请求参数?

转载 作者:行者123 更新时间:2023-11-28 06:56:52 26 4
gpt4 key购买 nike

我正在使用 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 传递给响应闭包吗?或者以任何其他方式访问它?

最佳答案

您可以像这样检索参数:

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

关于swift - 如何在响应闭包中访问 Alamofire 请求参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com