简体   繁体   English

Swift 3:如何在ALamofire 4的请求正文中添加或删除参数?

[英]Swift 3: How to add or remove parameters in Request Body in ALamofire 4?

I am using Alamofire library for REST API calls. 我将Alamofire库用于REST API调用。 I have a Request Body of type 我有一个类型的请求正文
Dictionary(String, Any) . Dictionary(String,Any) There are few objects in the Request Body that are common for some APIs. 在请求主体中,很少有某些API通用的对象。

For eg: 1st API call contains following parameters in the request body. 例如:第一个API调用在请求正文中包含以下参数。

var hotel = HotelParameter()
var food = foodParameter()
var address = addressParameter()

class RequestParameters: NSObject{

func parameter() -> NSDictionary {

   var parameter : [String : Any] = [:]
   parameter["hotels"] = hotel.params()
   parameter["foodType"] = food.params()
   parameter["address"] = address.params()

   return parameter as! NSDictionary
}

Now in 2nd API call I have to pass only " hotels " and " address " in the RequestParameter. 现在,在第二个API调用中,我只需要在RequestParameter中传递“ hotels ”和“ address ”。 My problem is: How to add or remove any extra parameter in the Alamofire Request Body? 我的问题是: 如何在Alamofire请求正文中添加或删除任何其他参数?

Since I cannot add Request Body for 'n' number of Requests, there has to be a single RequestParameter which will get modified according to the api calls. 由于我无法为n个请求添加请求正文,因此必须有一个RequestParameter会根据api调用进行修改。 There can be extra or single Parameter(s) in the Body. 主体中可以有额外或单个参数。 Mostly " hotels " will be a common parameter for all Request Body. 通常,“ 酒店 ”将是所有请求正文的通用参数。

I have tried a lot to solve this, But I get exception because it cannot parse some JSON response. 我已经尝试了很多方法来解决此问题,但是却出现异常,因为它无法解析某些JSON响应。 I have created functions to hit the api calls and I am passing the parameters like this. 我已经创建了函数来调用api调用,并且我正在传递这样的参数。

var requestParam = RequestParamters()

Alamofire.request(url,
                      method: .post,
                      parameters: requestParam.parameter(),
                      encoding: JSONEncoding.default, headers: headers)
        .responseJSON(completionHandler: { (data : DataResponse<Any>) in

I am not sure, I got your requirement right. 我不确定,我对您的要求是否正确。 But as per my understanding, you have to hit one API multiple times, and the parameter shall be different every time. 但是根据我的理解,您必须多次点击一个API,并且每次参数都应该不同。 So just write a method which'll take parameter as a method argument. 因此,只需编写一个将参数作为方法参数的方法。 Here is the sample code as per your requirement. 这是根据您的要求的示例代码。

func getAllHotels(_ params:Dictionary, callback:@escaping (Dictionary<String, Any>, Error?)->Void)
{
     let parameters: Parameters = params

    Alamofire.request(baseUrl + "/getHotels", method: .post,parameters: parameters, encoding: URLEncoding.default).responseJSON    { response in
        debugPrint("All Response from API: \(response)")
        switch response.result
        {
        case .success(let value):
            callback(value as! Dictionary, nil)
        case .failure(let error):
            callback([:], error)
        }
    }
}

/** Now call the above method with your required parameters **/

I found out Two ways to do it. 我发现了两种方法。

  1. Create an addExtraParams :[String : Any] = : type of Dictionary and add the key : value pair you need in this. 创建一个addExtraParams:[String:Any] =:字典类型,并在其中添加所需的key : value对。

  2. Create Requests functions for respective apis and just update the value of the required parameters using the object you get after logging. 为相应的api创建请求函数,并仅使用登录后获得的object来更新所需参数的值。

For eg: 例如:

var user = response.object as! Person
var request = RequestParameters()
request.hotel.name = user.hotel_name

Update the values before the Alamofire request in the function that you have created. 在您创建的函数中,在Alamofire请求之前更新值。

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

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