iOS 网络监测

项目中经常会遇到需要获取当前的网络状态,自己就简单的封装了一下。

  • 基于AFNetworking的网络监测

1.import "NetworkStatus.h"

#import 
#import "AFNetworking.h"

typedef void(^netStateBlock)(NSInteger netState);

@interface NetworkStatus : NSObject

+ (instancetype)sharedNetManager;

/**
 *  网络监测
 *  @param block 判断结果回调
 *  @return 网络监测
 */
+ (void)netWorkState:(netStateBlock)block;

@end

2.import "NetworkStatus.m"

#pragma mark - 网络监测
+ (instancetype)sharedNetManager {
    static dispatch_once_t once;
    static NetworkStatus *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

#pragma mark----网络检测
+ (void)netWorkState:(netStateBlock)block {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status== 0 || status == -1) {
            block(status);
        }else{
            block(status);
        }
    }];
}

3.调用

[NetworkStatus netWorkState:^(NSInteger netState) {
        
        switch (netState) {
            case 1:{
                NSLog(@"手机流量上网");
            }
                break;
            case 2:{
                NSLog(@"WIFI上网");
            }
                break;
            default:{
                NSLog(@"没网");
            }
                break;
        }
    }];

4.网络状态

 AFNetworkReachabilityStatusUnknown          = -1,  //未知的网络
 AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
 AFNetworkReachabilityStatusReachableViaWWAN = 1,   //2G,3G,4G
 AFNetworkReachabilityStatusReachableViaWiFi = 2,   //wifi网络

github地址

你可能感兴趣的:(iOS 网络监测)