解压之后将
Reachability.h
和Reachability.m
文件拖入自己的项目中在
AppDelegate.m
中引入Reachability.h
在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions NS_AVAILABLE_IOS(3_0);
方法里添加观察者监听网络状态改变的通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 监听网络状态改变
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
// 创建Reachability
Reachability *connect = [Reachability reachabilityForInternetConnection];
// 开始监控网络,若网络状态改变, 就会发出通知kReachabilityChangedNotification
[connect startNotifier];
return YES;
}
// 处理网络状态改变
- (void)networkStateChange
{
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
switch ([reachability currentReachabilityStatus]) {
case 0://没有网
[[[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
case 1:
NSLog(@"WIFI网络");
break;
case 2:
NSLog(@"手机自带网络");
break;
default:
break;
}
}