【问题标题】:How to timeout or detect slow response in AFHTTPSessionManager in AFNetworking?如何在 AFNetworking 的 AFHTTPSessionManager 中超时或检测慢响应?
【发布时间】:2014-08-14 15:51:08
【问题描述】:

使用下面的代码,如果没有互联网连接,故障块会立即触发 - 这很好。但是如果有连接但没有互联网怎么办?

我读过这个问题:How to set a timeout with AFNetworking,它建议使用reachabilityManager,这个答案中的示例显示了使用-AFNetworking 2.0 queue request when device is offline with setReachabilityStatusChangeBlock does nothing

但是,如果我的模拟器或手机已连接到我的 wifi 网络但无法访问互联网(DNS、DHCP 或调制解调器问题),我的代码目前会继续尝试访问我的 API 很长时间。我没有下载任何东西,而且我知道我的脚本和服务器应该会在几秒钟内做出响应,所以我知道在 5 秒不活动后,出现了问题。

那么我可以安全地进行超时,还是可以在我当前的脚本中使用reachabilityManager 来检测脚本(不是互联网)是否无法访问,如果是,如何?

- (void)APICall:(NSMutableDictionary*)params {

    NSURL *baseURL = [NSURL URLWithString:BaseURLString];
    NSDictionary *parametersGetAuthCode = @{@"req": @"getauth"};

    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:APIscript parameters:parametersGetAuthCode success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *r = (NSHTTPURLResponse *)task.response;
            if ([r statusCode] == 200) {

            //do success stuff

            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];

        //do failure stuff

    }];

}

【问题讨论】:

  • “我知道我的脚本和我的服务器应该在几秒钟内响应” > 你永远不能在移动网络上做出这样的假设...... 3G / Edge 可能真的很慢
  • 在桥下,在大型建筑中进入旧酒吧,您的数据连接可能非常慢。所以你会阻止对你的用户的访问?
  • 我知道我的做法不对,但我宁愿我的用户超时,然后体验异常长时间的与服务器通信的尝试。

标签: ios objective-c afnetworking


【解决方案1】:

只需弄清楚您的应用程序的合理超时间隔是多少,然后在 AFHTTPSessionManager 请求序列化器上设置它。

[manager.requestSerializer setTimeoutInterval:20.0];  

向您的 UI 添加一些内容,例如 UIActivityIndi​​catorView 或“正在下载...”消息,以便用户知道正在发生某些事情。

【讨论】:

    【解决方案2】:

    在 Swift 中,您可以使用以下代码设置超时。

    manager.requestSerializer.timeoutInterval = 25
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2014-09-25
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 2016-02-19
      相关资源
      最近更新 更多