嗨,我仍然是Alamofire和json的新手。我只想询问如何处理成功响应的错误。以下是api对帖子请求的回复。
{
data = {
"cabinet_id" = 3289146811;
"created_at" = "2018-04-11T04:53:43.288023001Z";
"user_id" = 123abc;
};
}
但有时我因为服务器错误而得到以下回复
{
error = {
"http_status_code" = 400;
message = "Unable to proceed";
type = "rent_request_failed";
};
}
这就是我所做的
let url = "myurl"
let parameters = ["user_id": ""\(self.idPassed)"",
"cabinet_id": "\(self.stringPassed)"]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
if (response.result.isSuccess){
if let value = response.result.value {
//now success or failed always navigate to here
Helper.helper.switchToNavigationViewController(Navigation: "hundredpercent")
print(value)
}
//do your json stuff
} else if (response.result.isFailure) {
//Manager your error
switch (response.error!._code){
case NSURLErrorTimedOut:
//Manager your time out error
break
case NSURLErrorNotConnectedToInternet:
//Manager your not connected to internet error
break
default:
let alertt = UIAlertController(title: "Server Error!", message: "Please try again", preferredStyle: .alert)
alertt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction!) in
//need navigate here if error
Helper.helper.switchToNavigationViewController(Navigation: "qrcodescan")
}))
self.present(alertt, animated: true)
}
}
}
答案 0 :(得分:9)
通过在alamofire请求中添加
validate(statusCode: 200..<299)
来调用API时验证响应状态代码。
如果您的http状态代码位于区间200-299
中,它将验证成功,否则会导致失败。
// Call response handler method of alamofire
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).validate(statusCode: 200..<299).responseJSON(completionHandler: { response in
switch response.result {
case .success(let data):
Logs.DLog(object: "\n Success: \(response)")
// Do your code here...
case .failure(let error):
Logs.DLog(object: "\n Failure: \(error.localizedDescription)")
// Do your code here...
}
})
答案 1 :(得分:1)
这是我用来处理响应的一种方式。希望这会对你有所帮助。
class func Request(statusCallBack: @escaping (_ statusCode: Int) -> Void, successCallback: @escaping (_ result: AnyObject) -> Void, errorCallback: @escaping (_ error: Error) -> Void) {
Alamofire.request(url, method: method, parameters: params, encoding: encodingType, headers: headers).responseJSON { (responce) in
// Here checking the status code of response
if let status = responce.response?.statusCode {
if status == 401 && AppUserDefault.getAccessToken() != nil {
User.logout()
return
}
statusCallBack(status)
}
switch responce.result {
case .success(_):
if let result = responce.result.value {
successCallback(result as AnyObject)
} else {
errorCallback(NSError(domain: "Internal server error", code: 1002, userInfo: nil))
}
break
case .failure(let error) :
errorCallback(error)
break
}
}
}
答案 2 :(得分:0)
使用SwiftyJSON并尝试这样
switch response.result {
case .success:
if let value = response.result.value {
let json = JSON(value)
if ( response.response!.statusCode == 200 || response.response!.statusCode == 201) {
let localStatusCode = json["status"].intValue
if localStatusCode >= 400 {
if json["errors"] != JSON.null{
callback(json["errors"].stringValue, nil)
}else{
callback(json["message"].stringValue, nil)
}
}else {
callback(nil, json)
}
}else if response.response?.statusCode != 200 {
callback(json["error"].stringValue, nil)
}
}
case .failure(let error):
NSLog("Failure \(error),\(urlString)")
if(response.response?.statusCode == 401){
}
if let errorStr = response.data {
let errorJson = JSON(errorStr)
if(errorJson != JSON.null){
if errorJson["error"] != JSON.null{
callback(errorJson["error"].stringValue, nil)
}else{
callback(errorJson["message"].stringValue, nil)
}
}else {
callback(error.localizedDescription,nil)
}
}else {
callback("Error Connecting to Server", nil)
}
}
})