【发布时间】:2017-07-10 06:25:51
【问题描述】:
所以我一直在python中使用requests来进行api调用,目前是这样使用的:
import requests
data = {"tag":"hello","value":"ayush"}
r = requests.post('MY URl', data)
现在我想在 swift 中实现相同类型的 post api 调用,(以尽可能最短和最简单的方式)所以请你帮忙
【问题讨论】:
所以我一直在python中使用requests来进行api调用,目前是这样使用的:
import requests
data = {"tag":"hello","value":"ayush"}
r = requests.post('MY URl', data)
现在我想在 swift 中实现相同类型的 post api 调用,(以尽可能最短和最简单的方式)所以请你帮忙
【问题讨论】:
你问得又快又简单,这只是触发和忘记。如果您想处理响应,请参阅上面由Andreas 建议的HTTP Request in Swift with POST method。如需优雅的方法,请查看 Swift Talk Networking: POST Requests(这些讨论非常好)。
如果您使用的是 HTTP 与 HTTPS,则必须将项目的 Info.plist NSAppTransportSecurity 属性 Allow Arbitrary Loads 设置为 true。
let url = URL(string: "http://yourdomain.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "{\"tag\":\"hello\",\"value\":\"ayush\"}".data(using: .utf8)
URLSession.shared.dataTask(with: request).resume()
【讨论】:
最简单的方法是使用 Alamofire: POST request with a simple string in body with Alamofire - 但这需要在您的项目中添加一个额外的库
您也可以使用 Apple 提供的内部框架“手动”通过URLRequest / URLSession:HTTP Request in Swift with POST method
【讨论】: