实现网络状态监听的步骤
@property (nonatomic, strong) Reachability *reachability;
// 在通知中心注册观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkStatus) name:kReachabilityChangedNotification object:nil];
/**
* getNetworkStatus:监听到通知的回调方法
* kReachabilityChangedNotification:通知的类型,即网络状态发生改变时,触发通知
* object:传递给getNetworkStatus回调方法的参数
*/
// 获取并保存网络状态
self.reachability = [Reachability reachabilityForInternetConnection];
// 开始监听
[self.reachability startNotifier];
- (void)getNetworkStatus
{
if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus != NotReachable)
{
NSLog(@"是WIFI");
}
else if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus != NotReachable)
{
NSLog(@"是手机自带网络");
}
else
{
NSLog(@"网络有问题");
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.reachability stopNotifier];
self.reachability = nil;
}
实现网络状态监听的
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"----当前网络状态---%zd", status);
}];
/**
* status:表示当前网络的状态,是个枚举类型变量,具有以下取值
* AFNetworkReachabilityStatusUnknown = -1
* AFNetworkReachabilityStatusNotReachable = 0
* AFNetworkReachabilityStatusReachableViaWWAN = 1
* AFNetworkReachabilityStatusReachableViaWiFi = 2
*/
[manager startMonitoring];
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/qq_26583311/article/details/47129961