我AFNetworking
在我的应用程序中使用每个请求(例如登录、从 url 获取数据等)。
举个例子:一个用户点击登录按钮并且没有连接,如何立即显示一个UIAlertView
说错误的?唯一的方法是等待请求超时并执行failure
块?有没有办法立即检查是否有连接?
谢谢!
我AFNetworking
在我的应用程序中使用每个请求(例如登录、从 url 获取数据等)。
举个例子:一个用户点击登录按钮并且没有连接,如何立即显示一个UIAlertView
说错误的?唯一的方法是等待请求超时并执行failure
块?有没有办法立即检查是否有连接?
谢谢!
从 0.9 开始,AFHTTPClient
实际上内置了网络可达性(Apple 上述可达性代码的更简单接口)。只需包含SystemConfiguration
框架并用于-setReachabilityStatusChangeBlock:
在可达性状态更改时指定响应。
这些是添加AFNetworing类后AFNetworking
必须遵循的步骤才能利用-setReachabilityStatusChangeBlock:
SystemConfiguration.framework
到您的项目#import <SystemConfiguration/SystemConfiguration.h>
AFHTTPClient
在此子类中有一个子类,请在 init 函数中添加以下代码行 -[self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus 状态) { NSLog(@"改变了 %d", 状态); //你的代码在这里 }];
也许您可以使用“可达性”来确定设备是否已连接到网络。这是 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
}
我使用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];
}
}