Alamofire帖子请求。

问题描述 投票:0回答:1

你好,我读了很多关于alamofire post request in swift的问题和答案,但无法得到我真正想要的答案,我真正想要的是:Post request使用URLRequest和URLSession,我必须在URLRequest中分配一个HTTPBody,这个身体可以是一个结构的实例,符合编码或可编码,但在alamofire post request如何发送数据? 在哪里把你要发送的数据? 谢谢你,不要把它标记为重复我读了很多帖子,但没有找到答案。

ios swift xcode alamofire urlsession
1个回答
1
投票

使用Alamofire实现请求的方法有很多,这是一个简单的例子。

首先,你必须创建参数,URL从你的API和头。

let parameters = [
    "username": "foo",
    "password": "123456"
]

let url = "https://httpbin.org/post"

static private var headers: HTTPHeaders {
        get {
            return [
               "Authorization" : "Bearer \(Session.current.bearerToken ?? "")"
            ]
        }
    }

所以你从Alamofire调用函数,并传递你的数据。

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

:)


1
投票

Alamofire有非常好的文档 此处. 这说明了所有关于传递可编码参数的问题。下面是一个例子。

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

1
投票
    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)
        }
    }

0
投票
// 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 {

}
© www.soinside.com 2019 - 2024. All rights reserved.