#import "Reachability.h"
(1)使用同步的方式是比较简单,通过代码检查网络:
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus status = [reach currentReachabilityStatus];
(2)通过检查某个主机能否访问来判断当前网络是否可用:
Reachability *reach = [Reachability reachabilityWithHostName:@“www.baidu.com”];
NetworkStatus status = [reach currentReachabilityStatus];
ReachableViaWWAN 3G 网络
ReachableViaWiFi WiFi网络
NotReachable 无网络
(3)实时监测网络状态
@property(nonatomic,strong)Reachability*reachability;
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netStatusChanged:)name:kReachabilityChangedNotification object:nil];
self.reachability= [ReachabilityreachabilityWithHostName:@"www.baidu.com"];
[self.reachability startNotifier];
}
-(void)netStatusChanged:(NSNotification*)notification{
Reachability*currentStatus = [notificationobject];
NSParameterAssert([currentStatus isKindOfClass:[Reachability class]]);
NetworkStatus status = [currentStatus currentReachabilityStatus];
if(status==NotReachable) {
UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"温馨提示"message:@"网络不可用"delegate:nil cancelButtonTitle:@"确定"otherButtonTitles:nil];
[alert show];
return;
}
}