14

I am using alamofire for some time now, but I have never used a form data Post. Now I am stuck. I have 2 params (email, password) and don't know how POST them to server. Can anyone give me an example please?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Pan Mluvčí
  • 1,242
  • 2
  • 21
  • 42
  • 1
    What does the server expect? A JSON POST? A URL encoded POST? A multipart form data POST? All of these matter and all are detailed in the Alamofire [README](https://github.com/Alamofire/Alamofire). – cnoon Nov 23 '15 at 14:46
  • Hi there Cnoon :-) love your framework very much... well a form data post... i read the README but i can't figure out the solution for 2 strings with no URL path – Pan Mluvčí Nov 23 '15 at 15:05

3 Answers3

22

And here is a sample code for Alamofire 4.0 in Swift 3.0

    let url = "http://testurl.com"

    let parameters = [
        "email": "asd@fgh.hjk",
        "password": "55555"
    ]


    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
        switch response.result {
        case .success:
            if let value = response.result.value {
                print(value)
            }
        case .failure(let error):
            print(error)
        }
    }
Ahmad Ismail
  • 641
  • 7
  • 15
  • `URLEncoding.httpBody` will give more meaning. – Kumar C Nov 21 '17 at 07:04
  • 1
    You need to change the content also **x-www-form-urlencoded** in case its required.[Find More](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding) – iSrinivasan27 May 28 '18 at 09:58
13

So my solution is.... you have to specify the Parameter Encoding in Alamofire. So the code will look like this.

Swift 2.0

func registerNewUserFormData(completionHandler: (Bool, String?) -> ()){

        // build parameters
        let parameters = ["email": "test@test.cz", "password": "123456"]

        // build request
        Alamofire.request(.POST, urlDomain + "register", parameters: parameters, encoding: .URL).responseJSON { response in

            switch response.result {
            case .Success:
                print("Validation Successful")
                if let JSON = response.result.value {
                    print(JSON)
                }

            case .Failure(let error):
                print(error)

            }
        }
    }
Pan Mluvčí
  • 1,242
  • 2
  • 21
  • 42
6

Swift 5

let url = "http://testurl.com"

let parameters = [
    "email": "asd@fgh.hjk",
    "password": "55555"
]


AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
    switch response.result {
    case .success:
        if let value = response.result.value {
            print(value)
        }
    case .failure(let error):
        print(error)
    }
}
Mohammad Sadiq
  • 5,070
  • 28
  • 29