阿拉莫火邮政请求:



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

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

首先,您是否必须从 API 和标头创建参数、URL 和标头:

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

:)

Alamofire在这里有非常好的文档。这说明了传递可编码参数的所有内容。下面是一个示例:

AF.request("myRequestUrl", method: .post, parameters: encodableModel).responseString { print($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 {
}
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)
}
}

相关内容

  • 没有找到相关文章

最新更新