AFNetworking和没有互联网连接的情况
我使用AFNetworking
在我的应用程序中的每一个请求(如login,从url获取数据等)。
以此为例:用户点击loginbutton,并没有连接,如何即时显示一个UIAlertView
说错误? 唯一的方法是等待请求超时并执行failure
块? 没有办法立即检查是否有连接?
谢谢!
从0.9开始, AFHTTPClient
实际上具有内置的networking可访问性(与苹果公司的上述Reachability代码相比更简单)。 只要包含SystemConfiguration
框架并使用-setReachabilityStatusChangeBlock:
在可达性状态更改时指定响应。
在AFNetworking
中,为了利用setReachabilityStatusChangeBlock:
必须遵循以下步骤setReachabilityStatusChangeBlock:
添加AFNetworing类之后 –
- 将
SystemConfiguration.framework
添加到您的项目 - 在pch文件中添加
#import <SystemConfiguration/SystemConfiguration.h>
- 假设你在这个子类中有一个
AFHTTPClient
的子类,在init函数中添加下面AFHTTPClient
行代码 –
[self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus状态){ NSLog(@“changed%d”,状态); //你的代码在这里 }];
也许你可以使用“可达性”来确定设备是否连接到networking。 这里是链接到苹果文件。 : 可达性
例如 :
[[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 }
我使用AFNetworkingOperationDidFinishNotification
。 每当http请求失败时,popup警报并通知用户
- (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]; } }
如何使用可达性?
你可以检查你是否有一个合理的理由尝试连接,然后再做。
看起来像苹果示例项目可达性显示如何获得初始状态。