1.首先添加框架SystemConfiguration.framework。
2.苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
下载完后,导入项目中
3.在AppDelegate.h定义一个全局变量 @property BOOL isConnect; 判断网络状态
4.在AppDelegate.m增加通知中心:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
hostReach = [Reachability reachabilityForInternetConnection];
[self updateInterfaceWithReachability:hostReach];
[hostReach startNotifier];
5.通知中心响应的事件,并给isConnect 赋值(PS:每次网络改变都会调用这个函数)
-(void)reachabilityChanged:(NSNotification*)notification
{
// 1.检测wifi状态
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.检测手机是否能上网络(WIFI\3G\2.5G)
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判断网络状态
if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
self.isConnect = YES;
NSLog(@"有wifi%d",self.isConnect);
} else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
NSLog(@"使用手机自带网络进行上网");
self.isConnect = YES;
} else { // 没有网络
self.isConnect = NO;
NSLog(@"没有网络%d",self.isConnect);
}
}
6.程序启动是检测网络状态 ,并给isConnect 赋值
-(void)updateInterfaceWithReachability:(Reachability*)reach
{
//对连接改变做出响应的处理动作。
NetworkStatus status=[reach currentReachabilityStatus];
if (status== NotReachable) { //没有连接到网络就弹出提实况
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示"
message:@"请检查网络连接状态"
delegate:nil
cancelButtonTitle:@"好" otherButtonTitles:nil];
[alert show];
self.isConnect = NO;
NSLog(@"没网了%d",self.isConnect);
}else {
self.isConnect = YES;
NSLog(@"有网了%d",self.isConnect);
}
}
在想要检测网络状态的类里面,实例化AppDelegate对象,调用isConnect。
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
网友评论