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
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 = [Reachability reachabilityForInternetConnection];
//_netWorkDetect = [Reachability reachabilityWithHostName:@" www.baidu.com"];
//开始监测
[_netWorkDetect stopNotifier];
return YES;
}
-(void) netWorkChanged:(NSNotification *)notify
{
Reachability *currentReach = [notify object];
[_netWorkDetect stopNotifier];
return YES;
}
-(void) netWorkChanged:(NSNotification *)notify
{
Reachability *currentReach = [notify object];
//获取网络状态
//
NotReachable 无连接
// ReachableViaWiFi WiFi
// ReachableViaWWAN 3G等无线网络
NetworkStatus status = [currentReach currentReachabilityStatus];
// 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];
}
}
if (status == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
[alert show];
}
}