zoukankan      html  css  js  c++  java
  • 使用Reachability监测网络变化-陈鹏

    在appdelegate里面添加观察者,并启动监测

     // 使用通知中心监听kReachabilityChangedNotification通知
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name:kReachabilityChangedNotification object:nil];
        // 获取访问指定站点的Reachability对象
        reach = [Reachability
                               reachabilityWithHostName:@"www.crazyit.org"];
        // 让Reachability对象开启被监听状态
        [reach startNotifier];

    实现监听方法

    - (void)reachabilityChanged:(NSNotification *)note
    {
        // 通过通知对象获取被监听的Reachability对象
        Reachability *curReach = [note object];
        // 获取Reachability对象的网络状态
        NetworkStatus status = [curReach currentReachabilityStatus];
        if (status == NotReachable)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                            message:@"不能访问www.crazyit.org" delegate:nil
                                                  cancelButtonTitle:@"YES" otherButtonTitles:nil];
            [alert show];
        }
    }

    需要注意的是:Reachability在appdelegate里面需要作为全局变量,或者属性.这是因为Reachability是从mrc过渡过来的,虽然是arc版,但其中的内存管理使用的是弱引用,所以需要作为全局变量或者属性来强引用,以避免程序运行中释放掉

  • 相关阅读:
    一本通课后练习 / 高手训练
    毒瘤 dp 题做题记录
    埃及分数
    CF340E Iahub and Permutations
    NOI2020 SDOI 爆零记
    Codeforces *1400-1600 做题记录
    Codeforces Round #636 (Div 3) 题解
    Codeforces Round #634 (Div 3) 题解
    洛谷 P4231 三步必杀
    【洛谷】【线段树+位运算】P2574 XOR的艺术
  • 原文地址:https://www.cnblogs.com/sixindev/p/4538918.html
Copyright © 2011-2022 走看看