iOS 实时监测网络状态(通过Reachability)

在AppDelegate.m中

 1 @property (nonatomic, strong) Reachability *reach;
 2 
 3 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 4     
 5     // 监测网络情况
 6     [[NSNotificationCenter defaultCenter] addObserver:self
 7                                              selector:@selector(reachabilityChanged:)
 8                                                  name: kReachabilityChangedNotification
 9                                                object: nil];
10     Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
11     [reach startNotifier];
12     self.reach = reach;
13 }

通知触发执行的方法

 1 #pragma mark - 网络状态变化通知
 2 - (void)reachabilityChanged:(NSNotification*)note {
 3     
 4     Reachability* curReach = [note object];
 5     NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
 6     NetworkStatus status = [curReach currentReachabilityStatus];
 7     
 8     /*
 9      NotReachable = 0, 无网络连接
10      ReachableViaWiFi, Wifi
11      ReachableViaWWAN 2G/3G/4G/5G
12      */
13     if (status == NotReachable) {
14        
15        // 没有网络的更多操作 
16 // 实现类似接到电话效果   self.window.frame = CGRectMake(0, 40, __width, __height-40);
17         
18     } else if (status == ReachableViaWiFi) {
19         NSLog(@"Wifi");
20     } else {
21         NSLog(@"3G/4G/5G");
22     }
23 }
1 - (void)dealloc {
2     [_reach stopNotifier];
3     [[NSNotificationCenter defaultCenter] removeObserver:self];
4 }

完毕,亲测可用

原文地址:https://www.cnblogs.com/MengXY/p/7216314.html