Using FORM DATA with Alamofire

这一生的挚爱 提交于 2019-12-09 15:39:57

问题


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?


回答1:


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



回答2:


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)

            }
        }
    }



回答3:


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


来源:https://stackoverflow.com/questions/33869058/using-form-data-with-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!