我有这样的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]()
}
它成一个循环并被附加。
答案 0 :(得分:0)
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 {