user2039697 user2039697 - 2 months ago 36
Swift Question

How to write curl command in Swift with Alamofire?

I have the following curl command which works fine on the command line but I fail to write it in Swift.

curl -u web:web -k -i -d '{ "email":"","fbId":"FBXXXFB","accessToken":"accessNow","familyName":"FamName","givenName":"given"}' -H "Content-Type: application/json;charset=UTF-8" -X POST ''

When I try to translate this in Alamofire I always get an error from the server. So I assume that the auth works fine but something with the parameter is not correct as I need to send 5 parameters to the server.
How can I do that exactly?

Here is the code snippet:

func loginWithFacebook(loginEmail: String, facebookId: String, accessToken: String,familyName: String, givenName: String, completionHandler: (AnyObject?, NSError?) -> ()) {

//Basic HTTP auth
let user = "web"
let password = "web"

// let headers = ["Authorization": "Basic \(base64Credentials)"] not working
// let headers = ["web": "web"] not working

//example for a nested array query
let parameters = [
"loginEmail": loginEmail,
"facebookId": facebookId,
"accessToken": accessToken,
"familyName": familyName,
"givenName": givenName

parameters: parameters
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value, nil)
case .Failure(let error):
completionHandler(nil, error)
.authenticate(user: user, password: password)

I call this method in the following way:

self.restApi.loginWithFacebook(email, facebookId: facebookId, accessToken: accessToken, familyName: familyName, givenName: firstName) {responseObject, error in

print("responseobject printed loginUserWithFacebook() ")
print("error printed")

//get the JSON object
let response = responseObject as? [String:AnyObject]

//parse down the first layer of JSON object which is an NSDictionary (sometimes it is [AnyObject] )
if let result = response!["result"] as? [String: AnyObject]
print("self.result.count after calling loginUserWithFacebook()")

// self.getProfileFromUser()

The error response from the server:

responseobject printed loginUserWithFacebook()
info = "Required fields missing.";
result = {


In your cURL request, the body is JSON. However, your Alamofire code will send the request using URL-encoded parameters. Try using JSON instead:

    parameters: parameters,
    encoding: .JSON

Also note that your cURL request uses the keys email and fbId, but your Alamofire code uses loginEmail and facebookId. You may need to change those as well if your server doesn't support both.