- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotificationobject:nil];
self.hostReach =[ReachabilityreachabilityWithHostName:@"www.baidu.com"] ;
//開始監聽,會啓動一個runloop
[self.hostReach startNotifier];
}
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability *currReach = [noteobject];
NSParameterAssert([currReachisKindOfClass:[Reachability class]]);
//對連接改變做出響應處理動作
NetworkStatus status = [currReachcurrentReachabilityStatus];
//如果沒有連接到網絡就彈出提醒實況
self.isReachable = YES;
if(status == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡連接異常"message:nil delegate:nilcancelButtonTitle:@"確定"otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = NO;
return;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡連接信息"message:@"網絡連接正常"delegate:nil cancelButtonTitle:@"確定"otherButtonTitles:nil];
// [alert show];
[alert release];
self.isReachable = YES;
}
-(void)viewWillAppear:(BOOL)animated
{
[superviewWillAppear:YES];
AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(appDlg.isReachable)
{
NSLog(@"網絡已連接");//執行網絡正常時的代碼
}
else
{
NSLog(@"網絡連接異常");//執行網絡異常時的代碼
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡連接異常"message:nil delegate:nilcancelButtonTitle:@"確定"otherButtonTitles:nil];
[alert show];
[alert release];
}
}
這樣就可以檢查到在運行程序時網絡突然的中斷和連接。