iOS实现实时检测网络状态的示例代码

2020-01-20 23:50:28王冬梅

AppDelegate中的实现:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
 //添加一个系统通知 
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; 
 //初始化 
 self.internetReachability=[Reachability reachabilityForInternetConnection]; 
 //通知添加到Run Loop 
 [self.internetReachability startNotifier]; 
 [self updateInterfaceWithReachability:_internetReachability]; 
 return YES; 
} 

回调函数:


(void) reachabilityChanged:(NSNotification *)note 
{ 
 Reachability* curReach = [note object]; 
 NSParameterAssert([curReach isKindOfClass:[Reachability class]]); 
 [self updateInterfaceWithReachability:curReach]; 
} 
- (void)updateInterfaceWithReachability:(Reachability *)reachability 
{ 
 NetworkStatus netStatus = [reachability currentReachabilityStatus]; 
 switch (netStatus) { 
 case NotReachable: 
  NSLog(@"====当前网络状态不可达=======http://www.easck.com/xiaofeixiang"); 
  break; 
 case ReachableViaWiFi: 
  NSLog(@"====当前网络状态为Wifi=======博客园-Fly_Elephant"); 
  break; 
 case ReachableViaWWAN: 
  NSLog(@"====当前网络状态为3G=======keso"); 
  break; 
 } 
} 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。