天天看點

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;
}           

繼續閱讀