iosswiftalamofireafnetworking

How to Set requestSerializer in Alamofire


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.


Solution

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