iOS 网络状态的监测

#import "ViewController.h"

#import "Reachability.h"

//工程需要添加 Reachability.h 与 Reachability.m文件

@interface ViewController ()

 

 @property(nonatomic,strong)Reachability *reach;

 

@end

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

 

    // 判断能否连接到某一个主机 网址用于测试

    // http://www.baidu.com

    self.reach = [Reachability reachabilityWithHostName:@"baidu.com"];

    

    // 添加通知 监测网络状态

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

    

    // 开始监听

    [self.reach startNotifier];

}

 

- (void)dealloc

{

    // 停止监听

    [self.reach stopNotifier];

    

    // 移除监听 // 移除整个控制器里所有的监听

//    [[NSNotificationCenter defaultCenter] removeObserver:self];

    // 移除控制器里的kReachabilityChangedNotification监听

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

}

- (void)reachabilityChanged

{

    // 网络状态

    switch (self.reach.currentReachabilityStatus) {

        case NotReachable:

            NSLog(@"没有连接");

            break;

        case ReachableViaWiFi:

            NSLog(@"WiFi");

            break;

        case ReachableViaWWAN:

            NSLog(@"WWAN");

            break;

            

        default:

            NSLog(@"");

            break;

    }

}

 

@end

posted on 2015-09-11 22:32  飞断天涯  阅读(84)  评论(0)    收藏  举报

导航