【问题标题】:checking network reachability in real time实时检查网络可达性
【发布时间】:2013-08-09 17:27:09
【问题描述】:

当用户按下按钮时,我需要知道设备是否在那个瞬间连接到互联网——而不是他是否在 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 秒更新的相同标志。

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

【问题讨论】:

  • 您可以使用 NSURLRequest 向 google.com 发送标头请求。这应该很快。
  • 除非 Google.com 关闭。
  • @HAS 听起来不错,但我不确定如何创建标头请求。如果您在答案中输入一些代码,我会接受。谢谢。
  • 如果三秒是不可接受的延迟,多长时间可以接受?
  • @CarlVeazey 问题不在于延迟的长度;就是状态不是实时更新的。我有一个 if/then 语句,只有在有互联网连接的情况下,我才需要走一条路——目前,而不是 3 秒前。

标签: ios reachability


【解决方案1】:

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

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

所以您的设置可能如下所示:

YourClass.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);
}

【讨论】:

    【解决方案2】:

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

    我以前使用的 Reachabilty 扩展 (NPReachability) 允许 KVO 状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多