您的位置:首页 > 理论基础 > 计算机网络

ios网络连接状态监测

2015-06-22 21:32 639 查看
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];

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: