可达性:检测网络何时重新连接

时间:2014-01-26 08:40:32

标签: ios nsurlconnection reachability

我是iOS新手,刚刚开始研究它。我正在尝试实现网络可访问性,以检测网络何时断开连接以及何时通过使用第三方类别返回。我能够检测到网络丢失但我无法检测到网络在断开连接后何时恢复。我使用以下条件来检查正常工作的断开连接:

// NSURLConnectionDelegate method: Handle the connection failing
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   Reachability    *reachability    =   [Reachability reachabilityForInternetConnection];
   [reachability startNotifier];
   NetworkStatus   internetStatus  =   [reachability currentReachabilityStatus];

   if(internetStatus==NotReachable)
   {
     NSLog(@" Network Disconnected")
   }
}

我已从此链接下载了第三方可访问性类:https://github.com/tonymillion/Reachability

有人能建议我检测网络再次连接的方法吗?

3 个答案:

答案 0 :(得分:1)

您致电

[reachability startNotifier];

这意味着每次更改可达状态时,它都会发出kReachabilityChangedNotification。所以你现在需要的是订阅接收这个通知:

[[NSNotificationCenter defaultCenter]
 addObserver:self 
 selector:@selector(reachabilityStatusChanged:) 
 name:kReachabilityChangedNotification 
 object:nil];

并实施reachabilityStatusChanged:方法:

- (void)reachabilityStatusChanged:(NSNotification *)notice {
   Reachability    *reachability    =   [Reachability reachabilityForInternetConnection];
   NetworkStatus   internetStatus  =   [reachability currentReachabilityStatus];

   if (internetStatus != NotReachable)
   {
      // do what you need
   }

}

答案 1 :(得分:1)

您可以像这样简单地在班级中发布通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

然后,您可以使用thiis方法观察网络连接何时返回,即连接状态发生变化:

- (void) reachabilityChanged:(NSNotification *)note
{
 Reachability* currentReach = [note object];
 NSParameterAssert([currentReach isKindOfClass:[Reachability class]]);
  if (internetStatus != NotReachable)
  {
     // handle UI as per your requirement
  }

}

答案 2 :(得分:0)

从此处下载Reachability.h

https://developer.apple.com/Library/ios/samplecode/Reachability/Introduction/Intro.html

并订阅通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];