Alamofire post request:

Viewed 2771

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 .

4 Answers
    let apiEndpoint: String = "https://xyz"
    let headers = ["Content-Type" : "application/json","Variable":"ABC"
    var param = [String: Any?]()
    param["Command"] = "ResetPin"
    var cellNo = MobileNumberField.text
    param["Data"] = jsonToString(json: ["CELLNO":"cellNo"])
    AF.request(URL(string: apiEndpoint)!, method: .post, parameters: param as Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in

        switch response.result {
        case .success(let value):
            if let json = value as? [String: Any] {

                let data = JSON(json)

                if data["Status"].stringValue == "0" {
                    let alert = UIAlertController(title: "Error", message: data["Message"].stringValue, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "Ok", style: .destructive) { _ in
                        return
                    })
                    self.present(alert, animated: true)
                }
                else {
                    let jsonStr = data["Data"]

                    let dict = convertToDictionary(text: jsonStr!)

                    if let dictMain = dict {
                        if (JSON(dictMain)["ISADMIN"].stringValue == "YES"){
                            //Is Admin
                            self.performSegue(withIdentifier:"AdminFoundSegue", sender: self)
                        } else {
                            //Is not Admin
                            self.performSegue(withIdentifier:"ConnectYourAccountSegue", sender: self)
                        }
                    }
                }
            }
        case .failure(let error):
            print(error)
            let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .destructive) { _ in
                return
            })
            self.present(alert, animated: true)
        }
    }

Alamofire has really good documentation here. Which says all about passing encodable parameters. Here's an example:

AF.request("myRequestUrl", method: .post, parameters: encodableModel).responseString { print($0) }

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

:)

// Create url request
// Get your instance of codable struct model

do {
    let encoder = JSONEncoder()
    let data = try encoder.encode(yourCodableObject)
    your_urlRequest.httpBody = data
} catch {

}
Related