Rechability的简单使用

AppDelegate.m

#import "AppDelegate.h"
#import "Reachability.h"

@interface AppDelegate ()

@property (nonatomic, strong) Reachability *reachability;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 监听网络状态的改变
    [self networkChange];
    
    return YES;
}

// 监听网络变化
- (void)networkChange
{
    // 开启网络状况的监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    // 监听的链接
    self.reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 开始监听, 会启动一个Runloop
    [self.reachability startNotifier];
}

// 网络链接改变时会调用的方法
- (void)reachabilityChanged:(NSNotification *)note
{
    // 通过通知对象获取被监听的Reachability对象
    Reachability *currReach = [note object];
    NSAssert([currReach isKindOfClass:[Reachability class]], @"非Reachability类");
    
    //对连接改变做出响应处理动作
    NetworkStatus status = [currReach currentReachabilityStatus];
    
    //如果没有连接到网络就提醒实况
    if(status == NotReachable) {
        NSLog(@"AppDelegate - 网络连接异常");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"networkChangeNotification" object:nil userInfo:@{@"networkStatusKey" : @(NO)}];
    } else {
        NSLog(@"AppDelegate - 网络连接正常");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"networkChangeNotification" object:nil userInfo:@{@"networkStatusKey" : @(YES)}];
    }
}

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 监听网络状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange:) name:@"networkChangeNotification" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)networkChange:(NSNotification *)notification
{
    NSString *status = notification.userInfo[@"networkStatusKey"];
    
    if (status.boolValue) {         // 断网切换为正常状态
        NSLog(@"断网切换为正常状态");
    } else {                        // 正常切换为断网状态
        NSLog(@"正常切换为断网状态");
    }
}

@end

Demo:

https://github.com/RinpeChen/RechabilityDemoByRinpe

posted @ 2015-12-15 17:17  Rinpe  阅读(493)  评论(0编辑  收藏  举报