我正在尝试通过Alamofire向我的API提出Post请求,我可以在Postman中制作。
在Postman中,我的请求如下:
这将给出成功回复。
在我的应用程序中,我尝试通过以下功能执行此操作:
func postUserInterests(interests: [Interest], user: User, completionHandler: (([AnyObject]?, ErrorType?) -> Void)) {
let urlString = Constant.apiUrl().stringByAppendingFormat(Constant.apiPostUserInterests, String(user.userID!))
var selectedInterests = [Int]()
for interest in interests {
if (interest.selected){
selectedInterests.append(interest.id!)
}
}
// let parameters = ["interest_ids": selectedInterests]
let parameters = ["interest_ids": [1,2,3]]
Alamofire.request(.POST, urlString, parameters: parameters, headers: self.header).validate().responseJSON { request, response, result in
switch (result) {
case .Success(let value):
let json = JSON(value)
let jsonArray = json["data"].rawString()
print(jsonArray)
if let items:Array<Item> = Mapper<Item>().mapArray(jsonArray) {
completionHandler(items, nil)
} else {
completionHandler(nil, ApiError.ParseError);
}
case .Failure(let data, let error):
print(data)
print(error)
break
}
}
}
然而,这将拍摄到.Failure响应打印以下内容:
Optional(<7b226d65 73736167 65223a22 6d697373 696e6720 70617261 6d657465 72732122 7d>)
Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 422" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 422}
我做错了什么?我想将一个简单的整数数组发布到我的后端
答案 0 :(得分:0)
缺少'encoding:.JSON'部分:
Alamofire.request(.POST, urlString, parameters: parameters, headers: self.header, encoding: .JSON)