zoukankan      html  css  js  c++  java
  • iOS 实时监测网络状态(通过Reachability)

    在AppDelegate.m中

     1 @property (nonatomic, strong) Reachability *reach;
     2 
     3 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     4     
     5     // 监测网络情况
     6     [[NSNotificationCenter defaultCenter] addObserver:self
     7                                              selector:@selector(reachabilityChanged:)
     8                                                  name: kReachabilityChangedNotification
     9                                                object: nil];
    10     Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    11     [reach startNotifier];
    12     self.reach = reach;
    13 }

    通知触发执行的方法

     1 #pragma mark - 网络状态变化通知
     2 - (void)reachabilityChanged:(NSNotification*)note {
     3     
     4     Reachability* curReach = [note object];
     5     NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
     6     NetworkStatus status = [curReach currentReachabilityStatus];
     7     
     8     /*
     9      NotReachable = 0, 无网络连接
    10      ReachableViaWiFi, Wifi
    11      ReachableViaWWAN 2G/3G/4G/5G
    12      */
    13     if (status == NotReachable) {
    14        
    15        // 没有网络的更多操作 
    16 // 实现类似接到电话效果   self.window.frame = CGRectMake(0, 40, __width, __height-40);
    17         
    18     } else if (status == ReachableViaWiFi) {
    19         NSLog(@"Wifi");
    20     } else {
    21         NSLog(@"3G/4G/5G");
    22     }
    23 }
    1 - (void)dealloc {
    2     [_reach stopNotifier];
    3     [[NSNotificationCenter defaultCenter] removeObserver:self];
    4 }

    完毕,亲测可用

  • 相关阅读:
    Spring实现AOP
    js Form表单转json格式,及后台接收(多种方法)
    Java 网络编程
    分布式系统学习
    java消息中间件
    oracle Clob类型转换成String类型
    Oracle的CLOB大数据字段类型
    oracle wm_concat函数 列转行 分组函数
    Oracle trunc函数使用
    ajax异步提交文件
  • 原文地址:https://www.cnblogs.com/MengXY/p/7216314.html
Copyright © 2011-2022 走看看