23

AFNetworking在我的应用程序中使用每个请求(例如登录、从 url 获取数据等)。

举个例子:一个用户点击登录按钮并且没有连接,如何立即显示一个UIAlertView说错误的?唯一的方法是等待请求超时并执行failure块?有没有办法立即检查是否有连接?

谢谢!

4

5 回答 5

57

从 0.9 开始,AFHTTPClient实际上内置了网络可达性(Apple 上述可达性代码的更简单接口)。只需包含SystemConfiguration框架并用于-setReachabilityStatusChangeBlock:在可达性状态更改时指定响应。

于 2012-02-13T05:03:42.497 回答
28

这些是添加AFNetworing类后AFNetworking必须遵循的步骤才能利用-setReachabilityStatusChangeBlock:

  1. 添加SystemConfiguration.framework到您的项目
  2. 在 pch 文件中添加#import <SystemConfiguration/SystemConfiguration.h>
  3. 假设您AFHTTPClient在此子类中有一个子类,请在 init 函数中添加以下代码行 -
[self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus 状态) {
        NSLog(@"改变了 %d", 状态);
        //你的代码在这里
    }];
于 2012-07-23T11:56:47.077 回答
2

也许您可以使用“可达性”来确定设备是否已连接到网络。这是 Apple Doc 的链接。:可达性

例如 :

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
  //Your UIAlertView
}
于 2012-02-12T23:11:01.407 回答
2

我使用AFNetworkingOperationDidFinishNotification. 每次http请求都会失败,弹出alert并通知用户

- (void)addNetworkObserver
{
   [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(HTTPOperationDidFinish:) 
                                                name:AFNetworkingOperationDidFinishNotification 
                                              object:nil];
}

- (void)HTTPOperationDidFinish:(NSNotification *)notification 
{
   AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];
   if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
       return;
   }
   if (operation.error) {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                       message:@"Missing connection to the internet"
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];

       [alert show];
   }
}
于 2013-11-20T14:06:32.900 回答
0

如何使用可达性?

您可以在尝试连接之前检查是否有合理的理由尝试连接。

看起来Apple Sample Project for Reachability展示了如何获得初始状态。

于 2012-02-12T23:03:07.930 回答