苹果原生的——————————————————————————————————————
//创建的工具类
@interface NetworkTool : NSObject
/**
* 是否WIFI
*/
+ (BOOL)isEnableWIFI;
/**
* 是否3G
*/
+ (BOOL)isEnable3G;
@end
#import "NetworkTool.h"
#import "Reachability.h"
@implementation NetworkTool
// 是否WIFI
+ (BOOL)isEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL)isEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
// 监听网络状态发生改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
// 获得Reachability对象
self.reachability = [Reachability reachabilityForInternetConnection];
// 开始监控网络
[self.reachability startNotifier];
}
- (void)dealloc
{
[self.reachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)networkStateChange
{
NSLog(@"网络状态改变了");
[self checkNetworkState];
}
/**
* 监测网络状态
*/
- (void)checkNetworkState
{
if ([NetworkTool isEnableWIFI]) {
NSLog(@"WIFI环境");
} else if ([NetworkTool isEnable3G]) {
NSLog(@"手机自带网络");
} else {
NSLog(@"没有网络");
}
}
@end
AFN的——————————————————————————————————————
- (void)viewDidLoad {
[super viewDidLoad];
AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
[ manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status)
{
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi环境");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"手机自带网络");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有网络");
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@"网络异常");
break;
}
}];
//开始监测
[manager startMonitoring];
}
-(void)dealloc
{
//停止监测
[[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}