2015-05-12 29 views
0

我正在使用以下方法來檢查我的應用是否有連接。這很簡單,對我的需求很好。NSTimer? - 檢查連接iOS

+ (void)checkInternet:(connection)block 
{ 
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    request.HTTPMethod = @"HEAD"; 
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; 
    request.timeoutInterval = 10.0; 

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler: 
    ^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     block([(NSHTTPURLResponse *)response statusCode] == 200); 
    }]; 
} 

但是,我想要做的是如果狀態不返回200,我想再次檢查,至少幾次。以1秒的間隔完成此操作的最佳方法是什麼?

下面是我如何調用上述方法。

[self checkInternet:^(BOOL internet) 
    { 
     if (internet) 
     { 
      // "Internet" aka Google 
     } 
     else 
     { 
      // No "Internet" aka no Google 
     } 
    }]; 
+1

你爲什麼要檢查呢? – trojanfoe

+3

爲什麼不使用Reachability類? – cekisakurek

+1

只有當您打網絡服務時才檢查互聯網連接它可能會節省您的電池壽命。 –

回答

1

我使用Reachability檢測一般網絡連接問題(請參閱答案的結束)。我使用以下方法執行重試。

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay; 

您可以調整您的系統,如下所示,以獲得具有可選次數的重試的新類方法。

注意:未測試以下內容。這只是給你一個總的想法。

// Variable to track number of retries left. If you had a shared instance 
// a property would be easier. 
static NSUInteger maxConnectionTries = 0; 

// New method which lets you pass a retry count. 
+ (void)checkInternet:(connection)block withMaxTries:(NSUInteger)maxTries 
{ 
    maxConnectionTries=maxTries; 
    [self checkInternet:block]; 
} 

// Your original code extended to retry by calling itself when code 200 
// is seen on a delay of 1s. Defaults to old code when retry limit exceeded 
// or non 200 code received. 
+ (void)checkInternet:(connection)block 
{ 
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    request.HTTPMethod = @"HEAD"; 
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; 
    request.timeoutInterval = 10.0; 

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler: 
    ^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     if ([(NSHTTPURLResponse *)response statusCode] != 200 && 
      maxConnectionRetries > 0){ 
      maxConnectionRetries--; 
      [self performSelector:@selector(checkInternet:) withObject:block afterDelay:1.0]; 
     } 
     else{ 
      maxConnectionRetries = 0; 
      block([(NSHTTPURLResponse *)response statusCode] == 200); 
     } 
    }]; 
} 

對於互聯網連接的普遍檢測,最好使用可達性。見here

我從AppDelegate代碼啓動可達性處理程序,然後在發生連接性更改時發佈本地通知。這允許應用程序始終在viewWillAppearviewWillDisappear之內接收連接更改通知和瞬態視圖控制器,以便在本地通知註冊並取消註冊(如果他們對連接更改感興趣)。

+0

感謝您在這裏的幫助,這是有道理的!爲了在If/Else邏輯中清楚,我只想在響應代碼!= 200 – aherrick

+1

的時候重試,我錯了。更新的答案,以便當它!= 200 –

+0

正確,我只是說看你的代碼示例它的編碼方式:) – aherrick

0

FYI這裏是我想出了:

+ (void)checkInternet:(connection)block withMaxTries:(NSUInteger)maxTries 
{ 
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    request.HTTPMethod = @"HEAD"; 
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; 
    request.timeoutInterval = 10.0; 

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler: 
    ^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     if ([(NSHTTPURLResponse *)response statusCode] != 200 && 
      maxTries > 0){ 

      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ 

       [self checkInternet:block withMaxTries:maxTries - 1]; 
      }); 
     } 
     else{ 
      block([(NSHTTPURLResponse *)response statusCode] == 200); 
     } 
    }]; 
}