iOS的网络环境判断

网络环境的判断有两种方式
1、Reachability
2、AFNetWorking中 AFNetworkReachabilityManager

Reachability步骤
(1)导入Reachability类名
(2)初始化Reachability对象,HostName 尽量用一个比较稳定的网络
(3)添加观察者,接收网络环境发生改变的通知
(4)开始监测
(5)在通知中得到Reachability的对象

代码实例
//1 导入头文件

import "Reachability.h"

//2 创建Reachability对象 尽量用一个比较稳定的网站

     Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];

// 3 添加观察者 接收网络环境变化的通知

/
kReachabilityChangedNotification 网络环境发生改变 通知的名字
NetworkStatus 网络环境的枚举
-(NSString
)currentReachabilityString 网络环境的字符串
*/

  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:kReachabilityChangedNotification object:nil];

//4 开始监测
//-(BOOL)startNotifier; 开始通知监测
//-(void)stopNotifier; 监测结束

[reachability startNotifier];

// 5 得到通知中的reachability对象 获得网络状态
// notfication.object;得到reachability对象

  • (void)change:(NSNotification )notfication{
    // notfication.object;得到reachability对象
    // 5 得到通知中的reachability对象 获得网络状态
    Reachability
    reachability = notfication.object;
    NSLog(@"%@",[reachability currentReachabilityString]);
    NSString *status = @"";
    switch (reachability.currentReachabilityStatus) {

    case NotReachable:{
        status = @"无网络";
    }
    
        break;
    case ReachableViaWiFi:{
        status = @"WIFI网络";
    }
    
        break;
    case ReachableViaWWAN:{
        status = @"WAN网络";
    }
    
        break;
    
    default:
        break;

    }
    NSLog(@"%@",status);
    }

下面是第二种方法
AFNetWorking
(1)导入类库
(2)创建检测对象 类方法shareManager
(3)开始监测
(4)通过检测对象 获得检测结果 回调方法(setReachabilityStatusChangeBlock:)

代码实例
// 1) 导入类库

import "AFNetworking.h"

// 2) 初始化AFNetworkReachabilityManager对象

 AFNetworkReachabilityManager *reachabilityMannger =   [AFNetworkReachabilityManager sharedManager];

// 3)开始监测
// - (void)startMonitoring;
// - (void)stopMonitoring;

[reachabilityMannger startMonitoring];

// 4)获得监测的网络状态

  [reachabilityMannger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSString *result = @"";
    switch (status) {
        case AFNetworkReachabilityStatusUnknown:
            result = @"未知网络";
            break;
        case AFNetworkReachabilityStatusNotReachable:
             result = @"无网络";
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
             result = @"WAN";
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
             result = @"WIFI";
            break;

        default:
            break;
    }
       NSLog(@"%@",result);
}];

ps:以上两种方式都需要下载下载reachability或者AFNetworking
以searchafnetworking 为例
方法 :打开终端 pod searchafnetworking
-> AFNetworking (3.0.4)
A delightful iOS and OS X networking framework.
pod 'AFNetworking', '~> 3.0.4'



文/用爱之心解爱之毒(简书作者)
原文链接:http://www.jianshu.com/p/4fbce026418a
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文地址:https://www.cnblogs.com/jx66/p/5587201.html