我正在编写一个WEB API。
然而,即使有错误,在快速代码中,在Alamofire请求中,“isSuccess”总是等于true。
我应该在JSON中发送什么来让Alamofire检测到有错误? (is.Failure = true)。
服务器正在向我发送错误代码404,但它看起来总是成功:
Alamofire.request(.GET, Constants.Path.rootUrl + "/api/users", parameters: ["username" : usernameString, "limit":3] , headers: ["tb-token" : userToken!])
.responseJSON { _, _, result in
print(result.value)
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
self.tableView.hidden = false
self.resultsDict = result.value as! NSArray
let results = result.value
let resultsNumber = results!.count
self.numberOfResults.text = "Results(\(resultsNumber))"
self.numberOfResults.hidden = false
self.resultsN = resultsNumber
self.loadedMode = true
self.tableView.reloadData()
self.tableView.hidden = false
case .Failure(let data, let error):
print((error as NSError).localizedDescription)
}
}
[编辑] 我上传到Alamofire 3.0,但我仍然遇到同样的问题。 这是新代码:
Alamofire.request(.GET, Constants.Path.rootUrl + "/api/users", parameters: ["username" : usernameString, "limit":3] , headers: ["tb-token" : userToken!])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
let results = response.result
if let JSON = response.result.value {
if response.result.isSuccess == true {
print("Success with JSON: \(JSON)")
self.tableView.hidden = false
self.resultsDict = results.value as! NSArray
let resultsNumber = results.value!.count
self.numberOfResults.text = "Results(\(resultsNumber))"
self.numberOfResults.hidden = false
self.resultsN = resultsNumber
self.loadedMode = true
self.tableView.reloadData()
self.tableView.hidden = false
}
}
else {print("error")}
}
这是response.response:
Optional(<NSHTTPURLResponse: 0x7fa1bb216a50> { URL: http://teambuilding-adall.rhcloud.com/api/users?limit=3&username=adallo } { status code: 404, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "Keep-Alive";
"Content-Length" = 60;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 10 Oct 2015 23:32:13 GMT";
Etag = "W/\"3c-dR4AnAjVi0TRWls1iKAm7w\"";
"Keep-Alive" = "timeout=15, max=60";
"X-Powered-By" = Express;
} })
[最终编辑]我通过添加以下两行代码解决了这个问题:
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
答案 0 :(得分:0)
通过浏览Alamofire GitHub页面以及一般做法,您应该发送一个非200状态代码来指示失败。特定状态代码应与错误的类型或原因相对应。
通常您会发送4xx状态代码(e.x.400,403,404,409)。请在此处阅读要发送的状态代码:http://www.restapitutorial.com/httpstatuscodes.html