I am using Alamofire library for REST API calls. I have a Request Body of type
Dictionary(String, Any) . There are few objects in the Request Body that are common for some APIs.
For eg: 1st API call contains following parameters in the request body.
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. My problem is: How to add or remove any extra parameter in the Alamofire Request Body?
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. 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. I have created functions to hit the api calls and I am passing the parameters like this.
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. 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.
Create an addExtraParams :[String : Any] = : type of Dictionary and add the key : value
pair you need in this.
Create Requests functions for respective apis and just update the value of the required parameters using the object
you get after logging.
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.
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.