【问题标题】:Testing the internet connection is not working with Reachability测试互联网连接不适用于可达性
【发布时间】:2013-02-07 18:02:00
【问题描述】:

我正在使用更新的Reachability 库来测试是否可以访问互联网连接。我尝试记录一条消息以防互联网无法访问,但日志没有调试:

//Test the internet connection
Reachability* reach = [Reachability reachabilityForInternetConnection];
reach.unreachableBlock = ^(Reachability*reach)
{
    NSLog(@"Internet connexion unreachable");//Although Internet cnx is off, this message is not displayed
    return;
};

// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];

我是否误解了可达性库?互联网关闭时如何执行给定任务?谢谢。

P.S:我的iPad只有wifi,没有3G服务。

【问题讨论】:

    标签: ios reachability


    【解决方案1】:

    在 Swift 4 中使用 Alamofire 检查内部人员

    import Foundation
    import Alamofire
    
    class Connectivity {
    
       class func isConnectedToInternet() ->Bool {
            return NetworkReachabilityManager()!.isReachable
       }
    }
    

    然后调用这个函数

    if Connectivity.isConnectedToInternet() {
        print("Yes! internet is available.")
        // do some tasks..
    }
    

    【讨论】:

      【解决方案2】:

      实际上,您应该注册一个通知以接收更改的可达性:

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

      在此处查看 Apple 示例:http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/Classes_ReachabilityAppDelegate_m.html#//apple_ref/doc/uid/DTS40007324-Classes_ReachabilityAppDelegate_m-DontLinkElementID_4

      【讨论】:

      • 您好,感谢您的回复。实际上我发现不得不使用@selector 有时是没用的。请看看我的回答,它工作正常,完全符合我的要求。
      【解决方案3】:

      好的,我得到的最好方法是遵循 Apple 示例代码:

         //Test the internet connection
         Reachability* reach = [Reachability reachabilityForInternetConnection];
      
         NetworkStatus netStatus = [reach currentReachabilityStatus];
         //See if the reachable object status is "ReachableViaWifi"
      if (netStatus!=ReachableViaWiFi) {
          //If not
          NSLog(@"wifi unavailable");
          //Alert the user about the Internet cnx
          WBErrorNoticeView *notice = [WBErrorNoticeView errorNoticeInView:self.view title:@"Network Error" message:@"Check your internet connection."];
          notice.sticky = NO;
          [notice show];
          return;//Exit the method
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多