• 使用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版,但其中的内存管理使用的是弱引用,所以需要作为全局变量或者属性来强引用,以避免程序运行中释放掉

  • 相关阅读:
    杂项
    hdu 2094
    hdu acm 1004
    android 重装sdk或者系统的时模拟器出现can open ****
    使用Java模拟操作系统高优先级算法
    各种语法解释及用法
    枚举与结构
    闭包
    socket
    异常
  • 原文地址:https://www.cnblogs.com/sixindev/p/4538918.html
Copyright © 2020-2023  润新知