iOS / iPhone可达性 – 如何仅使用Reachability.m / .h来检查互联网是否丢失/无法访问

前端之家收集整理的这篇文章主要介绍了iOS / iPhone可达性 – 如何仅使用Reachability.m / .h来检查互联网是否丢失/无法访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前,我正在使用苹果可达性/ / .h的类,它可以工作,除了它通知我任何更改,其中,我想只通知用户,如果网络不可达.目前,如果我有一个互联网连接,然后松开网络告诉我.但是当您重新连接到网络时,它也会告诉我,我不想要.我想让它只有当有丢失/没有网络时才告诉我.

我相信这跟电话有关:

  1. - (void)viewWillAppear:(BOOL)animated
  2. {
  3. // check for internet connection
  4. [[NSNotificationCenter defaultCenter]
  5. addObserver:self
  6. selector:@selector(checkNetworkStatus:)
  7. name:kReachabilityChangedNotification
  8. object:nil];
  9.  
  10. internetReachable = [[Reachability
  11. reachabilityForInternetConnection] retain];
  12. [internetReachable startNotifier];
  13.  
  14. // check if a pathway to a random host exists
  15. hostReachable = [[Reachability reachabilityWithHostName:
  16. @"www.google.ca"] retain];
  17. [hostReachable startNotifier];
  18.  
  19. // now patiently wait for the notification
  20. }

调用 – [NSNotificationCenter addObserver:selector:name:object:]时,名称是否具有任何其他功能,然后是字面上的名称?这是我第一次使用NSNotificationCenter,所以我不太懂这件事情.

编辑:

这是我的checkNetworkStatus功能:(问题是我正在收到“NotReachable”,因为网络连接回来,NSAlert多次关闭)

  1. - (void) checkNetworkStatus:(NSNotification *)notice
  2. {
  3. // called after network status changes
  4. NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
  5. switch (internetStatus)
  6.  
  7. {
  8. case NotReachable:
  9. {
  10. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Network Failed" message:@"Please check your connection and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
  11. [alert show];
  12. NSLog(@"The internet is down.");
  13.  
  14. break;
  15.  
  16. }
  17. case ReachableViaWiFi:
  18. {
  19. NSLog(@"The internet is working via WIFI.");
  20.  
  21. break;
  22.  
  23. }
  24. case ReachableViaWWAN:
  25. {
  26. NSLog(@"The internet is working via WWAN.");
  27.  
  28. break;
  29.  
  30. }
  31. }
  32.  
  33. NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
  34. switch (hostStatus)
  35.  
  36. {
  37. case NotReachable:
  38. {
  39. NSLog(@"A gateway to the host server is down.");
  40.  
  41. break;
  42.  
  43. }
  44. case ReachableViaWiFi:
  45. {
  46. NSLog(@"A gateway to the host server is working via WIFI.");
  47.  
  48. break;
  49.  
  50. }
  51. case ReachableViaWWAN:
  52. {
  53. NSLog(@"A gateway to the host server is working via WWAN.");
  54.  
  55. break;
  56.  
  57. }
  58. }

}

解决方法

当状态发生变化时,可达到的通知将会发送通知,但是该通知的操作完全取决于您.如果您不想告诉用户网络已经回来,您就不需要.

NSNotificationCenter方法中的“name”参数指示您订阅通知.当一个对象发布通知时,它以特定的名称进行.

猜你在找的iOS相关文章