监听网络状态

  • 在项目中导入Reachability.h和Reachability.m文件,地址:Reachability

    监听网络状态_第1张图片

  • ViewController.h:

#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property (nonatomic, strong) Reachability *reach;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChange) name:kReachabilityChangedNotification object:nil];
    self.reach = [Reachability reachabilityForInternetConnection];
    [self.reach startNotifier];
    
}

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

- (void)netWorkChange
{
    /*
     NotReachable = 0,
     ReachableViaWiFi,
     ReachableViaWWAN
     */
    switch ([self.reach currentReachabilityStatus]) {
        case 0:
            NSLog(@"没有网");
            break;
        case 1:
            NSLog(@"WiFi");
            break;
        default:
            NSLog(@"蜂窝数据");
            break;
    }
}

@end

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