一、在 AppDelegate.m 中创建监听单例,并监听发起通知
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"AFNetworkReachabilityStatusNotification" object:nil userInfo:@{@"status" : @(status)}];
}];
[manager startMonitoring];
二、在任意地方接收状态通知,此非block通知,iOS9后无需移除监听,不会强引用
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveAFNetworkingReachabilityStatusNotification:) name:@"AFNetworkReachabilityStatusNotification" object:nil];
}
- (void)receiveAFNetworkingReachabilityStatusNotification:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
NSInteger status = [[userInfo valueForKey:@"status"] integerValue];
switch (status) {
// 未知网络
case AFNetworkReachabilityStatusUnknown:
// 无网络
case AFNetworkReachabilityStatusNotReachable:
{
NSLog(@">>>>>>>>无网络aa");
break;
}
// 蜂窝数据
case AFNetworkReachabilityStatusReachableViaWWAN:
// wifi
case AFNetworkReachabilityStatusReachableViaWiFi:
{
NSLog(@">>>>>>>>Wifiaa");
break;
}
}
}