问题
I am currently working on a project in swift
. I used Alamofire
for REST API
but to make it work i need to pass a parameter in requestSerializer
In AFNETWORKING
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
But i can't find anything for Alamofire
.
I'm new to swift please help me out.
回答1:
You can pass pass JSON
data as encoding parameters, Encoding
in Alamofire
is equivalent to AFJSONRequestSerializer
request = Alamofire.request(.POST, webServicesURL, parameters: parameters, encoding: .JSON, headers: self.headers)
If you want to handle JSON data on response, just request
//This will give you response in JSON
request?.responseJSON { response in
switch response.result
{
case .Success:
success(response: response.result.value)
case .Failure(let error):
failure(error: error)
}
}
requestJSON
is equivalent to AFJSONResponseSerializer
in Alamofire
OR If you want to pass custom headers, pass a dictionary as
let headers = [
"Content-Type": "application/json"
]
//Here we are passing the header in header parameter.
request = Alamofire.request(.POST, webServicesURL, parameters: parameters, encoding: .JSON, headers: self.headers)
回答2:
You can use encoding
tag in your request for this. Use like,
Alamofire.request("<url>", method: .post, parameters: parameters, encoding: JSONEncoding.default){(response:DataResponse<Any>) in
}
来源:https://stackoverflow.com/questions/38279260/how-to-set-requestserializer-in-alamofire