天天看点

IOS开发-网络监听以及网络状态更改

1.首先下载在官网下载Reachability,并将下载的文件导入到工程中,如下图。

IOS开发-网络监听以及网络状态更改

2.在需要使用文件中导入头文件

//引入头文件
#import "Reachability.h"
@interface SFBaseViewController ()
//声明属性
@property (nonatomic,strong) Reachability *hostReachability;
@end           

3.定义默认地址

//地址定义
#define MY_URL               @"你自己的地址"           

4.加入通信机制

-(void)viewDidLoad{
[super viewDidLoad];

//其余代码
//...
//其余代码


//加入观察者
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)name:kReachabilityChangedNotification object: nil];
//设置网络地址
NSString *remoteHostName = MY_URL;
//加入地址
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
//启动
[self.hostReachability startNotifier];


//其余代码
//...
//其余代码
}           

5.通信机制调用的方法

- (void)reachabilityChanged:(NSNotification *)no{
    Reachability* curReach = [no object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    switch (status)
    {     
      case NotReachable:
      {
        NSLog(@"====当前网络状态不可达=======");
        //这里定义延迟方法
        [self performSelector:@selector(netWarming:) withObject:nil afterDelay:0.5f];
        break;
      }
      default:
        NSLog(@"====当前网络连接中=======");
        //其他处理
        break;
    }
}
           

6.网络连接失败的延迟方法

//网络连接失败
-(void)netWarming:(id)sender{
  [SVProgressHUD  dismissWithCompletion:^{
        if (![[NSThread currentThread] isMainThread]){
                dispatch_async(dispatch_get_main_queue(), ^{
                  UIAlertAction *alert1=[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      }];
      UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"\n连接网络失败,请检查网络连接" preferredStyle:UIAlertControllerStyleAlert];
      [alert addAction:alert1];
      if([[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController isKindOfClass:[UIAlertController class]]==NO){
        [self presentViewController:alert animated:YES completion:nil];
      }
      });
  }else{
    UIAlertAction *alert1=[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"\n连接网络失败,请检查网络连接" preferredStyle:UIAlertControllerStyleAlert];
     [alert addAction:alert1];
      if([[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController isKindOfClass:[UIAlertController class]]==NO){
         [self presentViewController:alert animated:YES completion:nil];
       }
    }
  }];
}
           

增加各种网络判断(额外内容)

7.Reachability.h可以修改,使得可以检测各种网络状态

//可以通过修改这里来增加检测机制,
typedef enum : NSInteger {
    NotReachable = 0,
    ReachableViaWiFi,
    ReachableViaWWAN,
    RaeachableVia4G,
    ReachableVia2G,
    ReachableVia3G
} NetworkStatus;           

8.修改Reachability.m文件,请先搜索该方法位置,然后修改内容

#pragma mark - Network Flag Handling

- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
{
    PrintReachabilityFlags(flags, "networkStatusForFlags");
    if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
    {
        // The target host is not reachable.
        return NotReachable;
    }

    NetworkStatus returnValue = NotReachable;

    if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
    {
        /*
         If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi...
         */
        returnValue = ReachableViaWiFi;
    }

    if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
        (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
    {
        /*
         ... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
         */

        if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
        {
            /*
             ... and no [user] intervention is needed...
             */
            returnValue = ReachableViaWiFi;
        }
    }

    if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
    {
        /*
         ... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
         */

        returnValue = ReachableViaWWAN;
        float IOS_VERSION=[[[UIDevice currentDevice] systemVersion] floatValue];
        NSLog(@"版本号:%lf",IOS_VERSION);
        if (IOS_VERSION >= 7.0) {
            CTTelephonyNetworkInfo *phonyNetwork = [[CTTelephonyNetworkInfo alloc] init];
            NSString *currentStr = phonyNetwork.currentRadioAccessTechnology;
            if (currentStr) {
                if ([currentStr isEqualToString:CTRadioAccessTechnologyLTE]) {
                    return RaeachableVia4G;
                }else if ([currentStr isEqualToString:CTRadioAccessTechnologyGPRS]|| [currentStr isEqualToString:CTRadioAccessTechnologyEdge]){
                    return ReachableVia2G;
                }else{
                    return ReachableVia3G;
                }
            }
        }
        if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection) {
            if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired) {
                return ReachableVia2G;
            }
            return ReachableVia3G;
        }
        return ReachableViaWWAN;

    }

    return returnValue;
}           

继续阅读