2013-04-25 72 views
1

在iPhone中我是新手,我想知道如何在xcode中使用Reachability。 我繼續前往Reachability example並閱讀它,但瞭解它。 我創建了一個應用程序,並將Reachability.m和Reachability.h放入其中,但我不知道如何使用它。如何在xcode中使用Reachability進行評估Internet連接

請指導我。我想,當運行應用程序檢查網絡連接任何時間,運行此代碼:

if (isConnection) 
{ 
NSLog(@"Connection Success") 
} 
else 
NSLog(@"Connection has been lost") 

回答

2

你可以這樣做:

Reachability *reachability = [Reachability reachabilityForInternetConnection]; 
NetworkStatus internetStatus = [reachability currentReachabilityStatus]; 

現在檢查internetStatus變種,通過檢查它的價值。該值被定義爲:

typedef enum 
{ 
    // Apple NetworkStatus Compatible Names. 
    NotReachable  = 0, 
    ReachableViaWiFi = 2, 
    ReachableViaWWAN = 1 
} NetworkStatus; 

所以,你的情況:

if (internetStatus == NotReachable) 
{ 
    NSLog(@"Bazinga!"); 
} 
else 
{ 
    NSLog(@"Houston we have ignition"); 
} 
+0

我的朋友,當我在我的項目中添加Reachability.m和Reachability.h我得到很多錯誤!爲什麼? – fred 2013-04-25 06:25:06

+0

你可能忘了添加'SystemConfiguration'框架。 – Peres 2013-04-25 06:25:55

+0

不,我添加SystemConfiguration但我收到很多錯誤 – fred 2013-04-25 06:31:41

0

下載可達性類和關注這個代碼

internetReach = [[Reachability reachabilityForInternetConnection] retain]; 
[internetReach startNotifier]; 

然後我們將設置中創建的NetworkStatus變量可達性。

NetworkStatus netStatus = [internetReach currentReachabilityStatus]; 

最後我們將在交換機模塊中使用netStatus。

switch (netStatus) 
{    
    case ReachableViaWWAN: 
    { 
     break; 
    } 
    case ReachableViaWiFi: 
    { 
     break; 
    } 
    case NotReachable: 
    { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"We are unable to make a internet connection at this time. Some functionality will be limited until a connection is made." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
     [alert show]; 
     [alert release]; 
     break; 
    } 

} 

- (void) reachabilityChanged: (NSNotification*)note 
{ 
    Reachability* curReach = [note object]; 
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]); 

    NetworkStatus netStatus = [curReach currentReachabilityStatus]; 
    switch (netStatus) 
    { 
     case ReachableViaWWAN: 
     { 
      break; 
     } 
     case ReachableViaWiFi: 
     { 
      break; 
     } 
     case NotReachable: 
     { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"We are unable to make a internet connection at this time. Some functionality will be limited until a connection is made." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
      [alert show]; 
      [alert release]; 
      break; 
     } 
    } 
} 
+0

我的朋友internetReach它是什麼?指針??從哪個類? – fred 2013-04-25 10:35:13

+0

我的朋友,當我寫reachabilityChanged方法我得到錯誤! – fred 2013-04-25 10:38:17