Alamofire无法捕获错误

3
我正在使用Alamofire从我的服务器获取数据。然而,它没有捕获到错误,因为返回的错误是“nil”。我已经使用AFNetworking进行了测试,它可以正常工作。对于这两种操作,返回的状态码都是“401未授权”。我的代码有问题吗?
我正在使用GrapeAPI作为后端。它只会在请求失败时返回错误。 GrapeAPI
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,因此很难确定请求是否失败。

2
在调用.response()之前,您需要显式调用.validate() - mattt
@mattt,可以这样做。Alamofire 默认采用这种方式的设计,而 AFNetworking 却没有,这是有什么原因吗? - Azuan
是的,在这种情况下,显式选择加入更好。 - mattt
2个回答

4

正如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
    }

阅读这份详细的解释(感谢!)以获取更多信息。


0

Alamofire 不会将 401 Unauthorized 视为错误,因为它是一个有效的返回值。在您的注释代码中,您正在为错误分配一个值而不是检查它是否为错误,应该是:

Alamofire.request(.GET, "url", parameters: nil)
        .response { (a,b,data,error) in
        if error != nil{
            println(error.localizedDescription)
        } else {
            if let data = data{
               //You should probably use a switch statement here
               if data.statusCode == 401 {
                   println("Unauthorized")
               } else if data.statusCode == 200 {
                   println("Success")
               }
           }
        }

我不确定我是否正确理解了你的问题,但我希望能够帮到你!


更新了我的代码。那些是输出值。我没有给任何变量分配任何值 :) - Azuan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接