监测网络状态

在网络应用中,需要对用户设备的网络状态进行实时监控,有两种方法:

第一种:AFNetworkReachabilityManager

需要导入头文件 #import <AFNetworking.h>

+ (void)monitorNetworking {


    AFNetworkReachabilityManager *manage = [AFNetworkReachabilityManager sharedManager];


    [manage setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

      switch (status) {

          case AFNetworkReachabilityStatusUnknown: // 未知网络
          {

              NSLog(@"未知网络");

          }
              break;

          case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
          {

              NSLog(@"没有网络(断网)");

              [MBProgressHUD showError:@"网络异常,请检查网络设置!"];
          }
              break;

          case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
          {

              NSLog(@"手机自带网络");

          }
              break;

          case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
          {

              NSLog(@"WIFI");

          }
              break;

      }

    }];

    // 开始监控
    [manage startMonitoring];
}

第二种:Reachability

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/xuzb/p/8663613.html