zoukankan      html  css  js  c++  java
  • Reachability判断网络是否连接

    类似于一个网络状况的探针。

      [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
        
        hostReach = [[Reachability reachabilityWithHostName: @"hubj.cnblogs.com"] retain];
        [hostReach startNotifier];
        
        wifiReach=[[Reachability reachabilityForLocalWiFi]retain];
        [wifiReach startNotifier];

    - (void)reachabilityChanged: (NSNotification* )note {
        Reachability* curReach = [note object];
        NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
        
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        
        switch (netStatus)
        {
            case NotReachable:
            {
                NSLog(@"Access Not Available");
                break;
            }
                
            case ReachableViaWWAN:
            {
                NSLog(@"Reachable WWAN");
                break;
            }
            case ReachableViaWiFi:
            {
                NSLog(@"Reachable WiFi");
                break;
            }
        }

    }

    判断网络是否连接

    复制代码
    /***
    * 此函数用来判断是否网络连接服务器正常
    * 需要导入Reachability类
    */
    + (BOOL)isExistenceNetwork
    {
    BOOL isExistenceNetwork;
    Reachability *reachability = [Reachability reachabilityWithHostName:@""]; // 测试服务器状态

    switch([reachability currentReachabilityStatus]) {
    case NotReachable:
    isExistenceNetwork = FALSE;
    break;
    case ReachableViaWWAN:
    isExistenceNetwork = TRUE;
    break;
    case ReachableViaWiFi:
    isExistenceNetwork = TRUE;
    break;
    }
    return isExistenceNetwork;
    }
    复制代码

    实时通知网络状况

    复制代码
    /*
    * 在应用委托的方法didFinishLaunchingWithOptions中添加
    */

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    reachability = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
    [reachability startNotifier];
    ........
    return YES;

    /**
    *此函数通过判断联网方式,通知给用户
    */
    - (void)reachabilityChanged:(NSNotification *)notification
    {
    Reachability *curReachability = [notification object];
    NSParameterAssert([curReachability isKindOfClass:[Reachability class]]);
    NetworkStatus curStatus = [curReachability currentReachabilityStatus];
    if(curStatus == NotReachable) {
    [DOIN_Util logFax:@"连接失败"];
    }
    }
  • 相关阅读:

    windows+php+redis的安装
    redis配置
    vim常用快捷键
    php数组的操作技巧
    python3与mysql数据库连接方式
    linux下删除文件夹,修改文件夹下所有文件的权限命令
    Linux下 “.tar.gz”格式的解压与压缩
    Linux解压tar.gz文件时提示gzip:stdin:not in gzip format 错误
    Ubuntu 18.04中安装docker,再在docker中安装mysql,及遇见问题
  • 原文地址:https://www.cnblogs.com/worldtraveler/p/4708051.html
Copyright © 2011-2022 走看看