iOS 開發 網絡實時監測

首先在AppDelegate.h添加頭文件"Reachability.h",導入框架SystemConfiguration.frame 
下面是代碼:

- (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;

    }

   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

{

   [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];

       

    }


}

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章