【问题标题】:AFNetworking issue with JSONRequestJSONRequest 的 AFNetworking 问题
【发布时间】:2013-09-05 17:47:16
【问题描述】:

我正在使用 AFNetworking 从服务器获取 JSON。 我的问题是,如果会话过期,服务器会回复字符串“NOSESSION”。

这是我的代码:

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request


                                  success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){


                                      NSArray *jsonArray =[JSON valueForKey:@"posts"];

                                        //DOING SOMETHING WITH jsonArray
                                        // in case that the response is NOSESSION do something                                        



                                  }

                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){




                                       }];

[operation start];

我的问题是请求失败,因为响应不是字符串。 错误信息:

Failed Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

有没有办法知道响应字符串? (我不介意在失败中捕获它我只想知道会话何时过期)

【问题讨论】:

    标签: ios json afnetworking


    【解决方案1】:

    你可以检查你的 NSHTTPURLResponse 的 statusCode。当你的服务器遇到这样的错误时,他通常会返回一个 statusCode。

    示例: 403:禁止 404页面不存在 500:内部服务器错误。

    您可以检查 HTTP statusCode 是否在 200 和 400 之间。==> 没有错误

    if(response.statusCode < 400 && response.statusCode > 200) {
        // do normal stuff 
    } else {
        // handle error
    }
    

    您可以在此处找到有关 HTTP 状态代码的更多信息: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

    【讨论】:

    • 我的问题不在于错误代码。我的问题是我想知道服务器的响应。也许数据库已关闭。如果数据库已关闭或用户已过期会话,我将如何理解/
    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 2013-01-05
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多