gpt4 book ai didi

ios - Alamofire 没有发现错误

转载 作者:可可西里 更新时间:2023-11-01 00:52:56 24 4
gpt4 key购买 nike

我正在使用 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

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,因此检查请求是否失败非常困惑。

最佳答案

正如 Matt 在评论中提到的,我需要在调用 .response() 之前添加 .validate()。这是设计使然。最终代码如下:

Alamofire.request(.GET, "url", parameters: nil)
.validate()
.response { (a,b,data,error) in
// error won't be nil now
// and statusCode will be 401
}

阅读this detailed explanation (谢谢!)了解更多信息。

关于ios - Alamofire 没有发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30906297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com