在iOS開發(fā)中我們需要考慮應(yīng)用程序需要對應(yīng)用設(shè)備的網(wǎng)絡(luò)狀況實時偵測,一方面,讓用戶了解自己當(dāng)前的網(wǎng)絡(luò)狀態(tài) 另一方面也增強了用戶體驗,那么我們怎么實現(xiàn)呢?
[官方示例程序] https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
我們將Reachability.h 和 Reachability.m 加到自己的項目中
并引用 SystemConfiguration.framework
網(wǎng)絡(luò)的幾種狀態(tài)
// the network state of the device for Reachability 2.0.
typedef enum {
NotReachable = 0, //無連接
ReachableViaWiFi, //使用3G/GPRS網(wǎng)絡(luò)
ReachableViaWWAN //使用WiFi網(wǎng)絡(luò)
} 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.
// 創(chuàng)建網(wǎng)絡(luò)探測對象
Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 想通知中心注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange:) name:kReachabilityChangedNotification object:nil];
// 開啟通知監(jiān)控
[reach startNotifier];
}
// 網(wǎng)絡(luò)狀況發(fā)生改變后,執(zhí)行該方法
- (void)networkChange:(NSNotification *)noti {
self.alertVC = [UIAlertController alertControllerWithTitle:@"網(wǎng)絡(luò)提示" message:@"當(dāng)前網(wǎng)絡(luò)狀況有變更" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[_alertVC dismissViewControllerAnimated:YES completion:nil];
}];
[_alertVC addAction:action1];
Reachability * reach = [noti object];
// 判斷當(dāng)前網(wǎng)絡(luò)是否可達(dá),可達(dá)則繼續(xù)后邊的判斷:通過哪種途徑到達(dá),不可達(dá),直接返回,不再執(zhí)行后邊的代碼
if ([reach isReachable]) {
NSLog(@"網(wǎng)絡(luò)可達(dá)");
} else {
NSLog(@"網(wǎng)絡(luò)有故障");
_alertVC.message = @"當(dāng)前網(wǎng)絡(luò)有故障";
[self presentViewController:_alertVC animated:YES completion:nil];
return;
}
if ([reach isReachableViaWiFi]) {
NSLog(@"通過WIFI到達(dá)");
_alertVC.message = @"當(dāng)前網(wǎng)絡(luò)是無線網(wǎng),為您加載高清資源";
[self presentViewController:_alertVC animated:YES completion:nil];
} else if ([reach isReachableViaWWAN]) {
NSLog(@"通過基站到達(dá)");
_alertVC.message = @"當(dāng)前網(wǎng)絡(luò)是流量,正在為您節(jié)省流量";
[self presentViewController:_alertVC animated:YES completion:nil];
} else {
NSLog(@"通過其他到達(dá)");
_alertVC.message = @"當(dāng)前使用未知網(wǎng)絡(luò)";
[self presentViewController:_alertVC animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end