网络监听使用APPLe的
Demo下载 http://download.csdn.net/detail/aa741649143/6210755
Reachability
需要添加这个文件包
同时还要添加框架:SystemConfiguration.framework
代码:
@property (retain,nonatomic)Reachability *WIFIreach;
//初始化
self.WIFIreach = [Reachability reachabilityForInternetConnection];
//或者:self.WIFIreach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
//开始监听,会启动一个run loop
[self.WIFIreach startNotifier];
//接收网络环境变化的通知 消息名称(固定)为:kReachabilityChangedNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
-(void) reachabilityChanged :(NSNotification *) notification
{
Reachability *curr = [notification object];
if ([curr isMemberOfClass:[Reachability class]]) {
[self showState];
// NetworkStatus state = [curr currentReachabilityStatus];
// NSString *stateDesc;
// switch (state) {
// case NotReachable :
// stateDesc = @"无可用连接";
// [self.switch3G setOn:NO animated:YES];
// [self.switchWIFI setOn:NO animated:YES];
// break;
// case ReachableViaWiFi :
// stateDesc = @"WIFI";
// [self.switch3G setOn:NO animated:YES];
// [self.switchWIFI setOn:YES animated:YES];
// break;
// case ReachableViaWWAN :
// stateDesc = @"2G/3G";
// [self.switch3G setOn:YES animated:YES];
// [self.switchWIFI setOn:NO animated:YES];
// break;
//
// }
// self.textField.text = stateDesc;
}
}
-(void)viewWillAppear:(BOOL)animated
{
[self showState];
}
-(void) showState
{
//检查当前网络状态
Reachability *currentReachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
NetworkStatus state = [currentReachability currentReachabilityStatus];
NSString *stateDesc;
switch (state) {
case NotReachable :
stateDesc = @"无可用连接";
[self.switch3G setOn:NO animated:YES];
[self.switchWIFI setOn:NO animated:YES];
break;
case ReachableViaWiFi :
stateDesc = @"WIFI";
[self.switch3G setOn:NO animated:YES];
[self.switchWIFI setOn:YES animated:YES];
break;
case ReachableViaWWAN :
stateDesc = @"2G/3G";
[self.switch3G setOn:YES animated:YES];
[self.switchWIFI setOn:NO animated:YES];
break;
}
self.textField.text = stateDesc;
}
Demo下载 http://download.csdn.net/detail/aa741649143/6210755