iOS Swift 2 - 失败时的Alamofire打印响应值

时间:2016-01-18 19:41:43

标签: ios swift alamofire

我正在使用Alamofire来处理我的http请求,但是我无法从未通过验证的请求中收到错误消息

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
            .validate(statusCode: 200..<300)
            .responseJSON { response in

                switch response.result {
                case .Success:
                    // response.result.value returns JSON

                case .Failure(let error):
                    // response.result.value returns nil
                }
        }

如果我收到错误代码400和其他错误,如何获取数据(JSON)。即使请求不成功,API也会在正文中发送数据。

2 个答案:

答案 0 :(得分:1)

只需删除您的状态代码验证

代码:

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
      .responseJSON { 
      response in
            let statusCode = response.response.statusCode
            switch statusCode {
            case 200..<300:
                // Success
            case 404:
                // not found
            default: 
                // something else
            }
    }

答案 1 :(得分:1)

跟随SaiCYLi,只有获得响应数据的方法是避免使用验证 参见Alamofire中的Result.swift 有阻挡者。

public var value: Value? {
    switch self {
    case .Success(let value):
        return value
    case .Failure:
        return nil
    }
}

我想对你发表评论,而不是回答。但我的声誉不到50岁。抱歉。