zoukankan      html  css  js  c++  java
  • iOS 检测网络状态

    1.为什么要检测网络状态?

    1.1 让用户知道自己的网络状态,防止用户埋怨"这个应用太垃圾,获取数据那么慢"

    1.2 根据用户的网络状态,智能处理,提升用户体验

    例如某些手机浏览器,检测到用户网络是2G/3G时,会自动切换为无图模式

    2.手动触发

    2.1 首先下载苹果的示例程序Reachability, 取得示例程序里的Reachability.h和Reachability.m, 添加到自己项目里

    代码如下

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    {

        // 检测WIFI状态

        Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

        // 检测手机联网状态(2G/3G/WIFI)

        Reachability *conn = [Reachability reachabilityForInternetConnection];

        

        if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

            NSLog(@"当前连着WIFI");

        }else{ //无WIFI

            if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G网络

                NSLog(@"当前连着2G/3G网络");

            }else{ //无2G/3G网络

                NSLog(@"当前没联网");

            }

         }

    }

    2.2 实际应用中,不会让用户手动去检测网络状态,下面用通知实现实时检测网络状态

    @property (nonatomic,strong) Reachability *coon;

       // 添加通知

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

        self.coon = [Reachability reachabilityForInternetConnection];

        // 发送通知

        [self.coon startNotifier];

    - (void)dealloc

    {

        [self.coon stopNotifier];

        [[NSNotificationCenter defaultCenter] removeObserver:self];

    }

    - (void)networkChange

    {

        [self checkNetworkState];

    }

    - (void)checkNetworkState

    {

        Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

        Reachability *conn = [Reachability reachabilityForInternetConnection];

        if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

            NSLog(@"当前连着WIFI");

        }else{ //无WIFI

            if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G网络

                NSLog(@"当前连着2G/3G网络");

            }else{ //无2G/3G网络

                NSLog(@"当前没联网");

            }

        }

    }

  • 相关阅读:
    yii2.0缓存的使用
    yii2.0框架where条件的使用
    yii2.0自带验证码使用
    spring中MessageSource的配置使用方法1[转]
    DOM、JDOM、DOM4J的区别
    探秘Java虚拟机——内存管理与垃圾回收
    MySQL开发规范和原则大全
    Java Classloader机制解析
    Junit之测试顺序---FixMethodOrder
    MySQL的btree索引和hash索引的区别
  • 原文地址:https://www.cnblogs.com/oumygade/p/4245349.html
Copyright © 2011-2022 走看看