一、說明
在網(wǎng)絡(luò)應(yīng)用中,需要對用戶設(shè)備的網(wǎng)絡(luò)狀態(tài)進(jìn)行實(shí)時(shí)監(jiān)控,有兩個(gè)目的:
(1)讓用戶了解自己的網(wǎng)絡(luò)狀態(tài),防止一些誤會(huì)(比如怪應(yīng)用無能)
(2)根據(jù)用戶的網(wǎng)絡(luò)狀態(tài)進(jìn)行智能處理,節(jié)省用戶流量,提高用戶體驗(yàn)
WIFI\3G網(wǎng)絡(luò):自動(dòng)下載高清圖片
低速網(wǎng)絡(luò):只下載縮略圖
沒有網(wǎng)絡(luò):只顯示離線的緩存數(shù)據(jù)
蘋果官方提供了一個(gè)叫Reachability的示例程序,便于開發(fā)者檢測網(wǎng)絡(luò)狀態(tài)
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
二、監(jiān)測網(wǎng)絡(luò)狀態(tài)
Reachability的使用步驟
添加框架SystemConfiguration.framework

添加源代碼

包含頭文件
#import "Reachability.h"
代碼示例:

#import "YYViewController.h"
#import "Reachability.h"
@interface YYViewController ()
@property (nonatomic, strong) Reachability *conn;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
self.conn = [Reachability reachabilityForInternetConnection];
[self.conn startNotifier];
}
- (void)dealloc
{
[self.conn stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)networkStateChange
{
[self checkNetworkState];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)checkNetworkState
{
// 1.檢測wifi狀態(tài)
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.檢測手機(jī)是否能上網(wǎng)絡(luò)(WIFI\3G\2.5G)
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判斷網(wǎng)絡(luò)狀態(tài)
if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
NSLog(@"有wifi");
} else if ([conn currentReachabilityStatus] != NotReachable) { // 沒有使用wifi, 使用手機(jī)自帶網(wǎng)絡(luò)進(jìn)行上網(wǎng)
NSLog(@"使用手機(jī)自帶網(wǎng)絡(luò)進(jìn)行上網(wǎng)");
} else { // 沒有網(wǎng)絡(luò)
NSLog(@"沒有網(wǎng)絡(luò)");
}
}
@end
// 用WIFI
// [wifi currentReachabilityStatus] != NotReachable
// [conn currentReachabilityStatus] != NotReachable
// 沒有用WIFI, 只用了手機(jī)網(wǎng)絡(luò)
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] != NotReachable
// 沒有網(wǎng)絡(luò)
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] == NotReachable