Send a POST request with JSON Object in swift 2.2 With Alamofire 3.0+

1k Views Asked by At

I want to send Json Object with .POST request in swift 2.2 using Alamofire for i code as below:

let dictionary: [String: AnyObject] = [
            "cUserEmail" : "[email protected]",
            "cUserPassword" : "abc",
            "cDeviceId" : "asdf"
        ]

        let url = NSURL(string: endPoint)

        let request = NSMutableURLRequest(URL:url!)
        request.HTTPMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)

        Alamofire.request(request)
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .Failure(let error):
                    print(error)
                case .Success(let responseObject):
                    print(responseObject)
                }
        }

But above mention code is not working. Previously, in objective-c i used code as below:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.securityPolicy.allowInvalidCertificates = YES;
 [manager POST:URLString parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

In short i want equivalent code for swift 2.2 with Alamofire.

2

There are 2 best solutions below

0
On

Try to use empty options for body like that :

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: [])
0
On

I found my solution by doing below method
hope it will work for you...

let dictionary: [String: AnyObject] = [
            "cUserEmail" : "[email protected]",
            "cUserPassword" : "abc",
            "cDeviceId" : "asdf"
        ]

let request2 = Alamofire.request(.POST, "http://localhost:8080/api/v1/register", parameters: dictionary, encoding: .JSON)
request2.validate()
request2.responseJSON(completionHandler: { (let response) in

    let data = response.data!
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        print ( "json is \(json)")

    } catch {
        print("error serializing JSON: \(error)")

        self.showAlert("Error :\(error)")
    }
})