首先在AppDelegate.h添加頭文件"Reachability.h",導(dǎo)入框架SystemConfiguration.frame
下面是代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//開啟網(wǎng)絡(luò)狀況的監(jiān)聽
[[NSNotificationCenter
defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification object:nil];
self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
//開始監(jiān)聽颅眶,會(huì)啟動(dòng)一個(gè)run loop
[self.hostReach startNotifier];
}
-(void)reachabilityChanged:(NSNotification *)note
{
Reachability *currReach = [note object];
NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
//對(duì)連接改變做出響應(yīng)處理動(dòng)作
NetworkStatus status = [currReach currentReachabilityStatus];
//如果沒有連接到網(wǎng)絡(luò)就彈出提醒實(shí)況
self.isReachable = YES;
if(status == NotReachable)
{
UIAlertView
*alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接異常" message:nil
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = NO;
return;
}
if (status==kReachableViaWiFi||status==kReachableViaWWAN) {
UIAlertView
*alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接信息" message:@"網(wǎng)絡(luò)連接正常"
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
//? ? ? ? [alert show];
[alert release];
self.isReachable = YES;
}
}
然后在每個(gè)頁面的viewWillAppear:加上:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(appDlg.isReachable)
{
NSLog(@"網(wǎng)絡(luò)已連接");//執(zhí)行網(wǎng)絡(luò)正常時(shí)的代碼
}
else
{
NSLog(@"網(wǎng)絡(luò)連接異常");//執(zhí)行網(wǎng)絡(luò)異常時(shí)的代碼
UIAlertView
*alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接異常" message:nil
delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
這樣就可以檢查到在運(yùn)行程序時(shí)網(wǎng)絡(luò)突然的中斷和連接。