【发布时间】:2015-09-03 13:22:03
【问题描述】:
我正在使用 Alamofire 从我的服务器获取数据。但是,它没有捕获错误,因为返回的错误是 nil。我已经用 AFNetworking 进行了测试,它工作正常。对于这两种操作,返回的状态码都是 401 Unauthorized 。我的代码有问题吗?
我在后端使用GrapeAPI。它所做的只是在失败请求时返回错误
葡萄API
error!('Unauthorized', 401)
AFNetworking
manager.GET("someUrl", parameters: nil, success: { (_, object) in
}, failure: { (operation, error) in
// These are the outputs. I'm not assigning any values
// error.localizedDescription = "Request failed: unauthorized (401)"
// statusCode = 401
})
阿拉莫火
Alamofire.request(.GET, "url", parameters: nil)
.response { (a,b,data,error) in
// These are the outputs. I'm not assigning any values
// error = nil
// data = {"error":"Unauthorized"}
// statusCode = 401
}
我可以使用 statusCode 检查失败。但我更喜欢检查错误对象。但是,由于 Alamofire 中的错误是 nil,因此检查请求是否失败是相当混乱的。
【问题讨论】:
-
您需要在调用
.response()之前明确调用.validate() -
@mattt 这行得通。为什么 Alamofire 被设计为默认以这种方式运行而 AFNetworking 不是?
-
是的,在这种情况下明确选择加入会更好。
标签: ios swift cocoa-touch afnetworking alamofire