IOS使用Reachability實時檢測網絡連接狀況

//在程序的啓動處,開啓通知

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

{

  //.....

//開啓網絡狀況的監聽

[[NSNotificationCenter defaultCenteraddObserver:self

         selector:@selector(reachabilityChanged:)

     namekReachabilityChangedNotification

   objectnil];

hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"retain];//可以以多種形式初始化

[hostReach startNotifier];  //開始監聽,會啓動一個run loop

        [self updateInterfaceWithReachabilityhostReach];

  //.....

}


// 連接改變

- (void) reachabilityChanged: (NSNotification* )note

{

Reachability* curReach = [note object];

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

[self updateInterfaceWithReachability: curReach];

}


//處理連接改變後的情況

- (void) updateInterfaceWithReachability: (Reachability*) curReach

{

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

        NetworkStatus status = [curReach currentReachabilityStatus];

    

if (status == NotReachable) {  //沒有連接到網絡就彈出提實況

UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"My App Name"

                              message:@"NotReachable"

                              delegate:nil

                              cancelButtonTitle:@"YES" otherButtonTitles:nil];

                              [alert show];

                              [alert release];

}


}

發佈了100 篇原創文章 · 獲贊 34 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章