Reachility第三方检测/监测网络状态

——检测—–
1.配置环境中导入框架这个框架.
2.导入第三方Reachiblity’
3.在viewconreoller中代码如下界面拖拽好

//
//  ViewController.m


 1.导入Reachablity框架
 2.导入系统的systemConfiguration.framework  允许应用程序访问设备的网络配置 设置
 3.Reachablity 类是用来检测 监听网络状态的  是苹果公司封装的第三方框架  是开源的

 */


#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *siteTextField;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

//测试     检测网络状态
- (IBAction)testAction:(id)sender {
    NSString * site = self.siteTextField.text;
    //创建访问站点的    网络监听   Reachability
    Reachability * reach = [Reachability reachabilityWithHostName:site];

    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            NSLog(@"无网络,不能访问站点");
            break;
        }
        case ReachableViaWiFi:{
            NSLog(@"使用wifi访问%@",site);
            break;
        }
        case ReachableViaWWAN:{
            NSLog(@"使用流量访问站点%@",site);
            break;
        }
        default:
            break;
    }

}
//测试wifi
- (IBAction)testWIFI:(id)sender {
    Reachability *reach = [Reachability reachabilityForLocalWiFi];
    if ([reach currentReachabilityStatus] != NotReachable) {
        NSLog(@"wifi网络已经连接");
    }else{
        NSLog(@"wifi网络不可用");
    }


}
//测试3g4g
- (IBAction)test3G4G:(id)sender {
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if ([reach currentReachabilityStatus] != NotReachable) {
        NSLog(@"流量访问已经连接");
    }else{
        NSLog(@"流量没有连接,不能访问");
    }

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end

——监测—–
操作步骤基本一样
viewcontroller中代码如下

//
//  ViewController.m
//  监测网络状态


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

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //初始化 可达性
    self.reachability =  [Reachability reachabilityForInternetConnection];
   //创建通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change) name:kReachabilityChangedNotification object:nil];
    //开始监听
    [self.reachability startNotifier];

    [self change];
}
-(void)change{
    //网络连接状态
   NetworkStatus  status =   [self.reachability currentReachabilityStatus];
    switch (status) {
        case NotReachable:
             NSLog(@"没有网络");
             break;

        case ReachableViaWiFi:
            NSLog(@"WIFI网络");
            break;

        case ReachableViaWWAN:
            NSLog(@"流量网络");

            break;

        default:
            break;
    }

}
-(void)dealloc{
    [self.reachability stopNotifier];
    //注销通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end




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