iOS开发和手机网络息息相关,有时候需要在用户手机端网络改变时做出一些操作,这时候就需要对手机网络实时监控,苹果为我们提供了一个很好的demo,Reachability类提供的接口能很好地检测网络变化;
1.下载Apple官方demo中的 Reachability类,并添加到工程中, 工工程中加入框架SystemConfiguration.framework.
2.在APPDelegate.m中加入以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//开启网络监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange:) name:kReachabilityChangedNotification object:nil];
_reach = [Reachability reachabilityForInternetConnection];
[_reach startNotifier];
return YES;
}
3.实现监听触发的方法
- (void)networkChange:(NSNotification *)notification {
Reachability *currReach = [notification object];
NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
//对连接改变做出响应处理动作
NetworkStatus status = [currReach currentReachabilityStatus];
//如果没有连接到网络就弹出提醒实况
if(status == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
return;
}
if (status == ReachableViaWiFi || status == ReachableViaWWAN) {
NSLog(@"网络连接正常");
}
}
最后,别忘了注销观察者:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论