2011-12-08 78 views
2

我有一個應用程序,顯示網絡可用性,每當有一些活動,如視圖更改。然而,我正在尋找在後臺運行的代碼來檢查網絡可用性,即使我將在同一屏幕上閒置,並且它必須顯示「網絡不可用/網絡可用」的消息後臺網絡檢查

回答

2

我使用這段代碼來檢測網絡可用性。我基本上宣佈本地增值稅來弄清楚我是否使用WiFi或3G網絡或互聯網是否可用。

通知以某些間隔&更新這些變量。您可以訪問這些BOOL變量以瞭解狀態。

- (void)checkNetworkStatus:(NSNotification *)notice 
{ 
    // called after network status changes 
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 

    switch(internetStatus) 
    { 
     case NotReachable: 
     { 
      //NSLog(@"The internet is down."); 
      self.internetActive = NO; 
      break; 
     } 
     case ReachableViaWiFi: 
     { 
      //NSLog(@"The internet is working via WIFI."); 
      self.internetActive = YES; 
      break; 
     } 
     case ReachableViaWWAN: 
     { 
      //NSLog(@"The internet is working via WWAN."); 
      self.internetActive = YES; 
      break; 
     } 
    } 

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus]; 
    switch (hostStatus) 
    { 
     case NotReachable: 
     { 
      //NSLog(@"A gateway to the host server is down."); 
      self.hostActive = NO; 
      break; 
     } 
     case ReachableViaWiFi: 
     { 
      //NSLog(@"A gateway to the host server is working via WIFI."); 
      self.hostActive = YES; 
      break; 
     } 
     case ReachableViaWWAN: 
     { 
      //NSLog(@"A gateway to the host server is working via WWAN."); 
      self.hostActive = YES; 
      break; 
     } 
    } 
    return; 
}