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(@"当前没联网");

            }

        }

    }

  • 相关阅读:
    U启动安装原版Win7系统教程
    U启动制作U盘启动盘详细教程
    大白菜装机版一键制作启动u盘教程
    git 学习笔记5--rm & mv,undo
    git 学习笔记4--.gitignore
    git 学习笔记3--status flow
    git 学习笔记2--How to create/clone a repository
    git 学习笔记1--config & help
    Ubuntu Mono 运行 Helloworld
    HttpClient 使用
  • 原文地址:https://www.cnblogs.com/oumygade/p/4245349.html
Copyright © 2011-2022 走看看