Search code examples
iosswiftxcodealamofireurlsession

Alamofire post request:


hello I have read a lot of questions and answers about alamofire post request in swift but could not get the answer I really want what I really want is that: Post request using URLRequest and URLSession I have to assign an HTTPBody in the URLRequest this body can be an instance of a struct that conforms to encodable or codable but in alamofire post request how to send data ? where to put the data you want to send ? thank you and don't mark it as duplicate I have read a lot of posts and didn't find an answer .


Solution

  • There are many ways to implement the requests using Alamofire, this is a simple example:

    First, do you have to create the parameters, URL from your API and headers:

    let parameters = [
        "username": "foo",
        "password": "123456"
    ]
    
    let url = "https://httpbin.org/post"
    
    static private var headers: HTTPHeaders {
            get {
                return [
                   "Authorization" : "Bearer \(Session.current.bearerToken ?? "")"
                ]
            }
        }
    

    So you call the function from Alamofire and pass your data:

    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
                response in
                switch (response.result) {
                case .success:
                    print(response)
                    break
                case .failure:
                    print(Error.self)
                }
            }
    }
    

    :)