最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Swift中Alamofire的http返回401时默认属于Success而不是Failure

iOS crifan 2990浏览 0评论

代码:

func getRequestRespJson(httpRequest:Alamofire.Request, mergedAllPara:Dictionary<String, AnyObject>, respJsonHandler: (Alamofire.Result<JSON, NSError>, mergedAllPara:Dictionary<String, AnyObject>) -> Void) {
    gLog.info(“httpRequest=\(httpRequest), mergedAllPara=\(mergedAllPara), respJsonHandler=\(respJsonHandler)”)
    dispatchBackground_async({
//        httpRequest.responseJSON(queue: BackgroundThread, completionHandler: { response in
        //validate will move status code out is of 200…299, to error
        httpRequest.validate().responseJSON(queue: BackgroundThread, completionHandler: { response in
            gLog.debug(“request=\(response.request), response=\(response.response), statusCode=\(response.response?.statusCode), result=\(response.result)”)
            let statusCode = response.response?.statusCode ?? 0
            gLog.debug(“statusCode=\(statusCode)”)
            switch response.result {
            case .Success(let value):
            case .Failure(let error):

此处调试期间发现:

服务器的http响应返回了401

但是却进入了.Success,而不是.Failure

以为是服务器端代码写错了。

但是调试的输出,证实了,statusCode是401

服务器端代代码没问题

看来好像是Alamofire的问题。

Alamofire/Alamofire: Elegant HTTP Networking in Swift

看到有个validate的事情

估计需要去主动的validate

然后去研究如何使用。

最后代码改为:

let BackgroundThread:dispatch_queue_t = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
func dispatchBackground_async(thingsTodo:()->()) {
    dispatch_async(BackgroundThread, thingsTodo)
}
    dispatchBackground_async({
//        httpRequest.responseJSON(queue: BackgroundThread, completionHandler: { response in
        //validate will move status code out is of 200…299, to error
        httpRequest.validate().responseJSON(queue: BackgroundThread, completionHandler: { response in

即可。

转载请注明:在路上 » [已解决]Swift中Alamofire的http返回401时默认属于Success而不是Failure

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.192 seconds, using 22.12MB memory