ios - Swift 4 - 使用 httpbody 的 Alamofire 发布请求
问题描述
我有这样的 Alamofire 发布请求:
var jsonArrayOfDictionaries = [[AnyHashable: Any]]()
let user = appDelegate.username
let password = appDelegate.password
let url = webservice + "PostTasks"
let credential = URLCredential(user: user!, password: password!, persistence: .forSession)
let headers = ["Accept": "application/json;odata=verbose", "Content-type": "application/json;odata=verbose"]
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: jsonArrayOfDictionaries, options: .prettyPrinted)
print(jsonData!)
//request.httpBody = jsonData
Alamofire.request(url, method: .post, headers: headers).authenticate(usingCredential: credential).responseJSON {
(response) in
switch response.result {
case .success:
if let value = response.result.value {
print(value)
OperationQueue.main.addOperation({
completion(true)
})
}else{
print("There is error in the server response")
completion(false)
}
case .failure (let error):
print("The NTLM request error is: ", error.localizedDescription)
completion(false)
}
}
我的问题是如何将 jsonData 变量添加到此请求的 httpbody 中?我已经研究过这个问题,所有的解决方案似乎都过时了。请帮忙!
这就是 jsonArrayOfDictionaries 的填充方式:
var jsonArrayOfDictionaries = [[AnyHashable: Any]]()
for i in 0..<cellHolder.count {
var jsonDict = [AnyHashable: Any]()
jsonDict["scheduleTaskID"] = cellHolder[i].scheduleTaskID
jsonDict["task"] = cellHolder[i].task
jsonDict["scheduledDate"] = cellHolder[i].scheduledDate
jsonDict["actualDate"] = cellHolder[i].actualDate
jsonDict["finishedDate"] = cellHolder[i].finishedDate
jsonDict["selected"] = (cellHolder[i].selected) ? 1 : 0
jsonDict["completedBy"] = appDelegate.username
jsonDict["sortOrder"] = cellHolder[i].sortOrder
jsonArrayOfDictionaries.append(jsonDict)
jsonDict = [AnyHashable: Any]()
}
它在一个循环中并被附加。
解决方案
1.改变
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: jsonArrayOfDictionaries, options: .prettyPrinted)
至
let jsonData = try JSONSerialization.jsonObject(with: jsonArrayOfDictionaries, options: []) as? [String : Any]
2. 将 jsonData 添加到您的请求中
Alamofire.request(url, method: .post, headers: headers, parameters: jsonData).authenticate(usingCredential: credential).responseJSON {
推荐阅读
- lucene - Lucene,内存中字符串的相关性/评分
- c# - 如何制作不聚焦的窗户亚克力?
- css - mso-line-height 和 mso-text-raise 在 Outlook 2013 中不起作用?
- python - 以 iso-8859-1 编码的 PDF
- javascript - 反应钩子:新状态值未反映在 setInterval 回调中
- reactjs - 如何在 React js 中将字符串附加到 API url onclick
- java - 当我添加“for”循环时,JSP 返回 null
- javascript - 如何向网站添加文本框以接受和处理大量用户数据
- java - “TypeError:form.set 不是函数”Java 无法访问 FormData 的函数
- javascript - Firebase 实时数据库 - foreach - 预计将在箭头函数结束时收到一个值