swift - 失败部分未返回 Alamofire 状态代码

标签 swift alamofire

我想在 Alamofire 请求的失败部分捕获一些状态响应。

以下代码:

let URL = "https://api.foo.bar"
Alamofire.request(URL, method: .post, parameters: parameters).responseObject { (response: DataResponse<UserResponse>) in
    switch response.result {
    case .success:
        // Yea, it worked.
    case .failure(let error):
        print(error)        
    }
    if let httpStatusCode = response.response?.statusCode {
        switch(httpStatusCode) {
        case 418:
            let alert = UIAlertController(title: "Whoops", message: "I't s a Teapot.", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
            break
        default:
            print("DEFAULT...")
            break
            //
        }
    }
}

由于某种原因返回 500 错误,但这不是来自 API,而是来自代码本身,但它是在哪里导致的呢?我不知道如何正确获取状态代码响应。

最佳答案

您可以从响应中访问状态代码,如下所示:

switch response.result {
    case .success(let jsonResult):
        // Case result OK
        print(jsonResult)
    case .failure(let error):
        // Case result Fail error
        if let resp = response.response, resp.statusCode == 401 {
            print("401 statusCode")
        }
}

关于swift - 失败部分未返回 Alamofire 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48516340/

相关文章:

ios - Xcode 9 - Alamofire pod 。命令/bin/sh 失败,退出代码为 1

ios - 如何在 Swift 3 中加载/删除带有动画的自定义 View

swift - 如何在 Swift 4 中使用 JSONEncoder 对字典进行编码

ios - UIBarButtonItem 禁用动画

ios - Binding Protocols with Associated Objects - 使用 Swift 进行面向协议(protocol)的编程

关联满足约束时的 swift 协议(protocol)方法

swift - 如何在 Alamofire 中处理多个网络调用

ios - 无法导入 Alamofire

ios - 创建复杂的 [String :AnyObject] for Alamofire parameters

.net - Swift - 错误的日期格式(JSON .NET)