Reachability检测网络状态

在现在的项目开发当中,监测网络是否正常非常有必要的。Reachability检测网络可以检测WiFi 3G 无线局域网

使用Reachability

下载Reachability,将Reachability添加到项目当中,在要检测网的类当中添加

#import <Reachability.h>

 

 //  开启网络状态的监听

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    

    self.reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];

    [self.reachability startNotifier];//开始监听

 

在方法reachabilityChanged:中写改变网络要做的事

//网络状态改变时调用方法

-(void)reachabilityChanged:(NSNotification *)note

{

    Reachability *currReach = [note object];

    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

    

    self.status = [currReach currentReachabilityStatus];

    

    self.isReachable = YES;

    

    switch (self.status) {

        case NotReachable:

        {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"网络状态" message:@"亲!没有网络哦!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

            [alertView show];

            

            self.isReachable = NO;

        }

            break;

            case ReachableViaWiFi:

        {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"网络状态" message:@"已连接WiFi!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

            [alertView show];

            self.isReachable = YES;

        }

            break;

            case ReachableViaWWAN:

        {

            self.isReachable = YES;

        }

            break;

        default:

            break;

    }

}

 

也可以直接写在AppDelegate当中。

posted @ 2015-01-06 10:49  我知道是菜鸟  阅读(179)  评论(0编辑  收藏  举报