天天看點

iOS Reachability監控網絡使用

//聯系人:石虎  QQ: 1224614774 昵稱:嗡嘛呢叭咪哄

第一步:     在AppDelegate.h添加頭檔案"Reachability.h"

第二步:     導入架構SystemConfiguration.frame

第三步:     下面是代碼:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

 {

 //開啟網絡狀況的監聽

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

 self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;

 //開始監聽,會啟動一個run loop

 [self.hostReach startNotifier];

 }

 -(void)reachabilityChanged:(NSNotification *)note

 {

 Reachability *currReach = [note object];

 NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

 //對連接配接改變做出響應處理動作

 NetworkStatus status = [currReach currentReachabilityStatus];

 //如果沒有連接配接到網絡就彈出提醒實況

 self.isReachable = YES;

 if(status == NotReachable)

 {

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡連接配接異常" 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:@"網絡連接配接資訊" message:@"網絡連接配接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

 //        [alert show];

 [alert release];

 self.isReachable = YES;

 }

 }

 然後在每個頁面的viewWillAppear:加上:

 -(void)viewWillAppear:(BOOL)animated

 {

 [super viewWillAppear:YES];

 AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];

 if(appDlg.isReachable)

 {

 NSLog(@"網絡已連接配接");//執行網絡正常時的代碼

 }

 else

 {

 NSLog(@"網絡連接配接異常");//執行網絡異常時的代碼

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡連接配接異常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

 [alert show];

 [alert release];

 }

 }

 這樣就可以檢查到在運作程式時網絡突然的中斷和連接配接。

繼續閱讀