实时检查网络可达性

时间:2013-08-09 17:27:09

标签: ios reachability

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

正如您在上面的评论中所希望的那样,使用" HEAD"请求。

  1. 让你的班级符合 NSURLConnectionDelegate
  2. 实施connection:didReceiveResponse:委托方法
  3. 可选择实施connection:didFailWithError:委托方法
  4. 所以您的设置可能如下所示:

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