在iOS开发中我们需要考虑应用程序需要对应用设备的网络状况实时侦测,一方面,让用户了解自己当前的网络状态 另一方面也增强了用户体验,那么我们怎么实现呢?
[官方示例程序] https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
我们将Reachability.h 和 Reachability.m 加到自己的项目中
并引用 SystemConfiguration.framework
网络的几种状态
// the network state of the device for Reachability 2.0.
typedef enum {
NotReachable = 0, //无连接
ReachableViaWiFi, //使用3G/GPRS网络
ReachableViaWWAN //使用WiFi网络
} NetworkStatus;
其实做起来是非常简单的我们在ViewController.m
#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property (nonatomic, strong) UIAlertController *alertVC;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 创建网络探测对象
Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 想通知中心注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange:) name:kReachabilityChangedNotification object:nil];
// 开启通知监控
[reach startNotifier];
}
// 网络状况发生改变后,执行该方法
- (void)networkChange:(NSNotification *)noti {
self.alertVC = [UIAlertController alertControllerWithTitle:@"网络提示" message:@"当前网络状况有变更" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[_alertVC dismissViewControllerAnimated:YES completion:nil];
}];
[_alertVC addAction:action1];
Reachability * reach = [noti object];
// 判断当前网络是否可达,可达则继续后边的判断:通过哪种途径到达,不可达,直接返回,不再执行后边的代码
if ([reach isReachable]) {
NSLog(@"网络可达");
} else {
NSLog(@"网络有故障");
_alertVC.message = @"当前网络有故障";
[self presentViewController:_alertVC animated:YES completion:nil];
return;
}
if ([reach isReachableViaWiFi]) {
NSLog(@"通过WIFI到达");
_alertVC.message = @"当前网络是无线网,为您加载高清资源";
[self presentViewController:_alertVC animated:YES completion:nil];
} else if ([reach isReachableViaWWAN]) {
NSLog(@"通过基站到达");
_alertVC.message = @"当前网络是流量,正在为您节省流量";
[self presentViewController:_alertVC animated:YES completion:nil];
} else {
NSLog(@"通过其他到达");
_alertVC.message = @"当前使用未知网络";
[self presentViewController:_alertVC animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end