2011-01-21 24 views
3

使用Reachability Class(來自Apple)檢查遠程主機的可用性是否明智?比方說,www.google.com使用Reachability檢查遠程主機的可用性是否明智?

,或者我應該使用

NSString *connectedString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"]]; 

if ([connectedString length] != 0) // Host Available 

這是最好的選擇,因爲我聽說可達性具有檢查主機的可用性錯誤?

回答

0

這裏是關於如何使用可達性的教程。 http://www.raddonline.com/blogs/geek-journal/iphone-sdk-testing-network-reachability/

NSString *connectedString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"]]; 

if ([connectedString length] != 0) // Host Available 

您提供的應該也可以使用,但可能不會得到預期的結果代碼..可達性更可靠..

+0

感謝所有。我以前見過這個鏈接。但是我聽說Reachability在檢查遠程主機可用性時有缺陷。那麼哪個是主機可用性的最佳選擇? – 2011-01-21 08:22:16

1

這是明智的檢查,如果您有任何互聯網連接第一,和我使用Reachability。我試圖與服務器進行連接,只有互聯網。

0

developer.apple.com下面的代碼可以幫助你..

// Create the request. 

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] 

         cachePolicy:NSURLRequestUseProtocolCachePolicy 

        timeoutInterval:60.0]; 

// create the connection with the request 

// and start loading the data 

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

if (theConnection) { 

    // Create the NSMutableData to hold the received data. 

    // receivedData is an instance variable declared elsewhere. 

    receivedData = [[NSMutableData data] retain]; 

} else { 

    // Inform the user that the connection failed. 

} 
10

這裏是檢查主機可達一個好辦法:如果主機處於脫機狀態,您將收到一些錯誤代碼

NSURLResponse *response=nil; 
    NSError *error=nil; 
    NSData *data = nil; 
    NSURLRequest *request = [NSURLRequest requestWithURL:your_url]; 

    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

error,nildatanilresponse變量。
如果主機在線並響應,則會出現一些response,dataerror==nil

+0

這是迄今爲止最好的策略! – 2012-05-29 18:00:31

3

可達性不會告訴你,如果遠程主機是可聯繫的。它只測試第一跳,即可以將數據包發送到路由器。如果路由器無法到達更廣泛的互聯網,可達性仍然會告訴您,您有無線連接。您必須實施其他建議的解決方案之一來測試「真實」可達性。

2

正如其他人所說,可達性檢測硬件的變化,而不是服務器的真實可用性。讀了很多帖子後,我突然想到了這個代碼。

下面是使用Reachability和URLConnection來確保連接可用或不可用的ReachabilityManager類的完整實現。請注意,這取決於可達性類(我使用的是Tony Million實現,但我確定它可以與Apple一起使用)

如果在模擬器中測試並啓用/禁用無線連接,您將看到它檢測(有時需要幾秒鐘)的連接/斷開。之前只有可達性類沒有用的東西。

我還在代碼的其餘部分中添加了一些比來自Reachability的通知更有效的通知。您可能想要以不同的方式處理此問題。

此外,這是一個單身人士,所以你可以從任何地方實例化。您可以將其轉換爲非靜態類並從AppDelegate實例化它。

我希望這對於任何人爲了可達性不能正確檢測可用性而中斷他/他的頭部都是有用的。

如果你們有時間爲它創建一些UnitTests,請讓我知道,這樣我們就可以共享更多知識。

只需創建一個新的NSObject類並複製此內容:

.H

#import <Foundation/Foundation.h> 
@interface ReachabilityManager : NSObject 

+ (void)startReachabilityWithHost : (NSURL *)hostName; 

@end 

.M

#import "ReachabilityManager.h" 
#import "Reachability.h" 

@implementation ReachabilityManager 

static ReachabilityManager *_sharedReachabilityManager; 
static Reachability *reachability; 
static NSURL *_hostName; 
static BOOL isServerReachable; 
+ (void)initialize 
{ 
    static BOOL initialized = NO; 
    if(!initialized) 
    { 
     initialized = YES; 
     _sharedReachabilityManager = [[ReachabilityManager alloc] init]; 
    } 
} 

+ (void)startReachabilityWithHost : (NSURL *)hostName{ 
    _hostName = hostName; 

    reachability = [Reachability reachabilityWithHostname:hostName.host]; 

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

+ (void)stopReachability{ 
    [reachability stopNotifier]; 
    [[NSNotificationCenter defaultCenter]removeObserver:kReachabilityChangedNotification]; 
} 

+(void)reachabilityChanged: (NSNotification *)notification{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     BOOL isServerCurrentlyReachable = NO; 
     do{ 
      isServerCurrentlyReachable = [self checkConnectivityToServer]; 
      BOOL wasServerPreviouslyReachable = isServerReachable; 
      isServerReachable = isServerCurrentlyReachable; 

      if (NO == wasServerPreviouslyReachable && YES == isServerCurrentlyReachable) 
      { 
       NSLog(@"REACHABLE!"); 
       [[NSNotificationCenter defaultCenter]postNotificationName:@"kNetworkReachabilityCustom" object:[NSNumber numberWithBool:YES]]; 
      } 
      else if (YES == wasServerPreviouslyReachable && NO == isServerCurrentlyReachable) 
      { 
       NSLog(@"UNREACHABLE!"); 
       [[NSNotificationCenter defaultCenter]postNotificationName:@"kNetworkReachabilityCustom" object:[NSNumber numberWithBool:NO]]; 
      } 
      [NSThread sleepForTimeInterval:5.0]; 
     }while(!isServerCurrentlyReachable); 
    }); 

} 


+(BOOL)checkConnectivityToServer{ 
    NSURLResponse *response; 
    NSError *error=nil; 
    NSData *data = nil; 
    NSURLRequest *request = [NSURLRequest requestWithURL:_hostName]; 

    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

    return (data && response); 

} 


@end 
相關問題