1

当用户按下按钮时,我需要知道设备是否在那一刻连接到互联网——而不是他是否在 3 秒前连接。在网络可达性发生变化后,可达性 (tonymillion) 通知器大约需要很长时间才能更新。

我认为我可以使用以下方法实时检查实际访问:

if (!([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable)) NSLog(@"reachable");
if ([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable) NSLog(@"not reachable");

但结果表明,实际上currentReachabilityStatus并没有检查互联网访问;它只检查延迟约 3 秒更新的相同标志。

现场实际检查网络访问的有效方法是什么?

4

2 回答 2

1

您是否尝试过将观察者置于可达性状态?

我曾经使用的 Reachabilty 扩展 ( NPReachability ) 允许 KVO 在状态上。

于 2013-08-09T17:36:22.460 回答
1

正如您在上面的评论中所希望的那样,这里是使用“HEAD”请求的解决方案。

  1. 使您的类符合 NSURLConnectionDelegate
  2. 实现connection:didReceiveResponse:委托方法
  3. 可选择实现connection:didFailWithError:委托方法

因此,您的设置可能如下所示:

你的班级.m

@interface YourClass () <NSURLConnectionDelegate>
@property (strong, nonatomic) NSURLConnection *headerConnection;
@end

@implementation YourClass

- (void)viewDidLoad {
    // You can do this in whatever method you want
    NSMutableURLRequest *headerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
    headerRequest.HTTPMethod = @"HEAD";
    self.headerConnection = [[NSURLConnection alloc] initWithRequest:headerRequest delegate:self];
}

#pragma mark - NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (connection == self.headerConnection) {
        // Handle the case that you have Internet; if you receive a response you are definitely connected to the Internet
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Note: Check the error using `error.localizedDescription` for getting the reason of failing
    NSLog(@"Failed: %@", error.localizedDescription);
}
于 2013-08-09T21:22:05.150 回答