ios网络连接状态监测

Reachability是苹果封装的一个用于监测网络状态的类,同时还可以检测出连接网络的类型(无连接,WiFi,3G),非常的轻巧,易用。

下载路劲:

苹果官方网站:http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

 github:https://github.com/tonymillion/Reachability

使用方法:

1.将解压出来的Reachability.h和Reachability.m添加到项目中。

2.添加SystemConfiguration.framework到项目中。

3.在要使用的地方把头文件Reachability.h import进来:

下面以在程序刚起来的时候(didFinishLaunchingWithOptions)使用为例:

//AppDelegate.m


 @interface AppDelegate (){
     Reachability *_netWorkDetect; 
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 网络变化时通过通知中心调用提示函数 netWorkChanged
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChanged:) name:kReachabilityChangedNotification object:nil];
    
    //获取监测器对象
    _ netWorkDetect = [Reachability reachabilityForInternetConnection];
    //_netWorkDetect = [Reachability reachabilityWithHostName:@" www.baidu.com"];
    //开始监测
     [_netWorkDetect stopNotifier];
    
    return YES;
}


-(void) netWorkChanged:(NSNotification *)notify
{
    Reachability *currentReach = [notify object];
    //获取网络状态
    // NotReachable 无连接
    // ReachableViaWiFi WiFi
    // ReachableViaWWAN  3G等无线网络
     NetworkStatus status = [currentReach currentReachabilityStatus];
    
   //网络无连接时,弹出警告视图
    if (status == NotReachable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值