使用苹果自带的Reachability监听网络状态

导入这两个文件先

Reachability.h
Reachability.m
 
 

//
//  ViewController.m
//  AppleReachablity
//
//  Created by hq on 16/4/18.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"
#import "Reachability.h"

@interface ViewController ()

@property(nonatomic,strong) Reachability *ablity;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self monitorNetWork];
 
}

//监听网络的变化
-(void) monitorNetWork{
    
    NSNotificationCenter *notification=[NSNotificationCenter defaultCenter];
    
    //让我们的netWorkChanged方法监听网络状态的变化
    [notification addObserver:self selector:@selector(netWorkChanged) name:kReachabilityChangedNotification object:nil];
    
    self.ablity=[Reachability reachabilityForInternetConnection];
    
    [self.ablity startNotifier];
    
}

-(void) netWorkChanged{
    
    //NotReachable = 0,
    //ReachableViaWiFi,
    //ReachableViaWWAN
    
    if (self.ablity.currentReachabilityStatus==NotReachable) {
        
        NSLog(@"未连接网络");
    }
    else if(self.ablity.currentReachabilityStatus==ReachableViaWiFi){
        
        NSLog(@"当前网络为wifi");
    }
    else{
        NSLog(@"手机自带网络");
    }

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(使用苹果自带的Reachability监听网络状态)