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

posted @ 2015-05-29 16:48  sixindev  阅读(231)  评论(0编辑  收藏  举报