计时器? - 检查连接 iOS

NSTimer? - Check Connection 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);
     }];
}

但是,如果状态不是 return 200,我想再检查一次,至少检查几次。以 1 秒为间隔执行此操作的最佳方法是什么?

下面是我调用上述方法的方式。

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

我使用 Reachability 来检测一般网络连接问题(请参阅答案结尾)。我使用以下方法执行重试。

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

您可以像下面这样调整您的系统以获得一个新的 class 方法,该方法具有可选的重试次数。

注意。未测试以下内容。只是给大家大概的思路。

// 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);
         }
     }];
}

对于 Internet 连接的一般检测,最好使用 Reachability。参见 here

我从我的 AppDelegate 代码启动可达性处理程序,然后在连接发生变化时发布本地通知。这允许应用程序始终在 viewWillAppearviewWillDisappear 中接收连接更改通知和瞬态视图控制器,以便在它们对连接更改感兴趣时注册和注销本地通知。

仅供参考,这是我想出的:

+ (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);
         }
     }];
}