网络状态的监控

几乎每个项目都会用到网络状态的监控,在无网络状态和网络切换时 WiFi 切换到 WWAN 模式,给用户提示。

这次就讲解一下,网络状态的监控在项目中是怎么使用的。
主要讲解第三方框架 Reachability,当然 AFNetworking 也是可以做网络状态监控的。


网络状态的监控_第1张图片
10.png

1.引入第三方框架:Reachability
2.对第三方框架进行封装成工具类,降低对项目的侵入性

.h 文件中

#import 
@interface WBNetWorkingTool : NSObject
+ (BOOL)isEnableWIFI; // wifi状态
+ (BOOL)isEnableWWAN; // 流量模式
@end

.m 文件中

#import "WBNetWorkingTool.h"
#import "Reachability.h"
@implementation WBNetWorkingTool
+ (BOOL)isEnableWIFI
{
     return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]!= NotReachable);
}
+ (BOOL)isEnable3G
{
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
@end

3.开始使用封装的工具类

1> 需要监听网络状态发生改变时发出通知

// 拥有一个属性
@property (strong,nonatomic) Reachability * reachability;

// 在 appdelegate 中进行监听
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
// 获得 Reachability
self.reachability = [Reachability reachabilityForInternetConnection];
// 开始监控网络
self.reachability startNotifier];

2> 要在 dealloc 中释放掉通知,并停止监控网络

- (void)dealloc
{
    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObsever:self];
}

3> 通知的动作

- (void)networkStateChange
{
    if([WBNetWorkingTool isEnableWWAN]){
        NSLog(@"流量模式");
    }else if([WBNetWorkingTool isEnableWIFI]){
        NSLog(@"WIFI");
    }else{
        NSLog(@"没有网络");
    }
} 

你可能感兴趣的:(网络状态的监控)