您的位置:首页 > 理论基础 > 计算机网络

在全局检测移动网络的变化

2016-09-06 00:00 375 查看
导入Reachability.h类

在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions里添加

#pragma mark == 监听网络状态

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

self.internetReachability=[Reachability reachabilityForInternetConnection];

[self.internetReachability startNotifier];

[self updateInterfaceWithReachability:_internetReachability];

AppDelegate.m里添加方法

- (void)reachabilityChanged:(NSNotification *)note

{

Reachability* curReach = [note object];

[self updateInterfaceWithReachability:curReach];

}

- (void)updateInterfaceWithReachability:(Reachability *)reachability

{

NetworkStatus netStatus = [reachability currentReachabilityStatus];

switch (netStatus) {

case 0:

{

//输出提示框

UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前无网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];

[alert show];

}

break;

case NotReachable:

NSLog(@"网络状态不可达");

break;

case ReachableViaWiFi:

NSLog(@"Wifi");

break;

case ReachableViaWWAN:

NSLog(@"3G");

break;

}

}

当网络状态发生变化时会调用该方法,无网络是弹出提示框
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络状态改变