全局网络检测
转载于:http://my.oschina.net/meilidashijie/blog/99533
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2 { 3 self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 4 5 //开启网络状况的监听 6 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; 7 8 self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ; 9 [self.hostReach startNotifier]; //开始监听,会启动一个run loop 10 11 self.window.rootViewController = self.tabBarController; 12 [self.window makeKeyAndVisible]; 13 return YES; 14 } 15 16 //网络链接改变时会调用的方法 17 -(void)reachabilityChanged:(NSNotification *)note 18 { 19 Reachability *currReach = [note object]; 20 NSParameterAssert([currReach isKindOfClass:[Reachability class]]); 21 22 //对连接改变做出响应处理动作 23 NetworkStatus status = [currReach currentReachabilityStatus]; 24 //如果没有连接到网络就弹出提醒实况 25 self.isReachable = YES; 26 if(status == NotReachable) 27 { 28 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:@"暂无法访问书城信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; 29 [alert show]; 30 [alert release]; 31 self.isReachable = NO; 32 } 33 else 34 { 35 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接信息" message:@"网络连接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; 36 [alert show]; 37 [alert release]; 38 self.isReachable = YES; 39 } 40 } 41 42 通过如上代码,在应用程序的任何一个界面都可以使用下面的单例来判断网络是否连接 43 44 [cpp] view plain copy 45 46 AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 47 if(appDlg.isReachable) 48 { 49 NSLog(@"网络已连接");//执行网络正常时的代码 50 } 51 else 52 { 53 NSLog(@"网络连接异常");//执行网络异常时的代码 54 } 55 56 然后就可以执行响应的操作了,这样使用监听的好处就是,不必在每一个需要检测网络链接情况的地方都写一大堆代码,只需要上面的监听,网络改变的时候,在任何一个地方都可以自定提醒用户。