获得网络状态和实时监控网络状态改变
2016-09-19 17:56
218 查看
Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。
Reachability 中定义了3种网络状态:
检测莫个特定站点的连接状况
检测当前网络环境
连接状态实时通知
我写的一个例子,给大家参考,希望对大家有所帮助
https://github.com/qcx123/NetworkMonitoring.git
Reachability 中定义了3种网络状态:
NotReachable 无连接 ReachableViaCarrierDataNetwork (ReachableViaWWAN) 使用3G/GPRS网络 ReachableViaWiFiNetwork (ReachableViaWiFi) 使用WiFi网络
检测莫个特定站点的连接状况
Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"]; switch ([r currentReachabilityStatus]) { case NotReachable: // 没有网络连接 break; case ReachableViaWWAN: // 使用3G网络 break; case ReachableViaWiFi: // 使用WiFi网络 break; }
检测当前网络环境
// 是否wifi + (BOOL) IsEnableWIFI { return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); } // 是否3G + (BOOL) IsEnable3G { return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); }
连接状态实时通知
#import "AppDelegate.h" #import "Reachability.h" @interface AppDelegate () { Reachability *hostReach; } @end @implementation AppDelegate - (void)reachabilityChanged:(NSNotification *)note { Reachability *curReach = [note object]; NSParameterAssert([curReach isKindOfClass:[Reachability class]]); NetworkStatus state = [curReach currentReachabilityStatus]; if (state == NotReachable) { [self alertWithMessage:@"没有网络"]; }else if (state == ReachableViaWiFi){ [self alertWithMessage:@"wifi网络"]; }else if (state == ReachableViaWWAN){ [self alertWithMessage:@"移动网络"]; } } - (void)alertWithMessage:(NSString *)message{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络状态" message:message delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil, nil]; [alert show]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 检测网络状态 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; [hostReach startNotifier]; return YES; }
我写的一个例子,给大家参考,希望对大家有所帮助
https://github.com/qcx123/NetworkMonitoring.git
相关文章推荐
- Hdu5893树链剖分(2016沈阳网络赛B)
- Unix网络编程之select实现服务器端程序
- Wiki_Android_网络工具类NetworkUtils
- Retrofit2.0+okhttp3实现缓存
- tcpdump抓取HTTP包
- hdu5892Resident Evil(2016沈阳网络赛A)
- 关于HttpURLConnection的一个疑问解析
- C++网络编程之socket
- 【Boost】boost库asio详解8——几个TCP的简单例子
- HttpServletResponse响应头与HttpServletRequest请求头及编码问题
- Linux网络编程知识点
- 原谅我是标题党-----centos6.3速度配置Internet网络
- 2016沈阳站网络赛题解
- java HttpsURLConnection请求报错
- httpClient中的三种超时时间设置
- 第一章 TCP/IP协议族
- http://www.myexception.cn/web/407976.html
- 数据链路层
- TCP/IP协议族
- https://my.oschina.net/lichhao/blog