1、說明ios
在網絡應用中,須要對用戶設備的網絡狀態進行實時監控,有兩個目的:緩存
(1)讓用戶瞭解本身的網絡狀態,防止一些誤會(好比怪應用無能)網絡
(2)根據用戶的網絡狀態進行智能處理,節省用戶流量,提升用戶體驗app
WIFI\3G網絡:自動下載高清圖片框架
低速網絡:只下載縮略圖post
沒有網絡:只顯示離線的緩存數據atom
蘋果官方提供了一個叫Reachability的示例程序,便於開發者檢測網絡狀態spa
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zipcode
2、監測網絡狀態server
Reachability的使用步驟
添加框架SystemConfiguration.framework
添加源代碼
包含頭文件
#import "Reachability.h"
代碼示例:
1 #import "YYViewController.h" 2 #import "Reachability.h" 3 4 @interface YYViewController () 5 @property (nonatomic, strong) Reachability *conn; 6 @end 7 8 @implementation YYViewController 9 10 - (void)viewDidLoad 11 { 12 [super viewDidLoad]; 13 14 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil]; 15 self.conn = [Reachability reachabilityForInternetConnection]; 16 [self.conn startNotifier]; 17 } 18 19 - (void)dealloc 20 { 21 [self.conn stopNotifier]; 22 [[NSNotificationCenter defaultCenter] removeObserver:self]; 23 } 24 25 - (void)networkStateChange 26 { 27 [self checkNetworkState]; 28 } 29 30 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 31 { 32 33 } 34 35 - (void)checkNetworkState 36 { 37 // 1.檢測wifi狀態 38 Reachability *wifi = [Reachability reachabilityForLocalWiFi]; 39 40 // 2.檢測手機是否能上網絡(WIFI\3G\2.5G) 41 Reachability *conn = [Reachability reachabilityForInternetConnection]; 42 43 // 3.判斷網絡狀態 44 if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi 45 NSLog(@"有wifi"); 46 47 } else if ([conn currentReachabilityStatus] != NotReachable) { // 沒有使用wifi, 使用手機自帶網絡進行上網 48 NSLog(@"使用手機自帶網絡進行上網"); 49 50 } else { // 沒有網絡 51 52 NSLog(@"沒有網絡"); 53 } 54 } 55 @end 56 57 // 用WIFI 58 // [wifi currentReachabilityStatus] != NotReachable 59 // [conn currentReachabilityStatus] != NotReachable 60 61 // 沒有用WIFI, 只用了手機網絡 62 // [wifi currentReachabilityStatus] == NotReachable 63 // [conn currentReachabilityStatus] != NotReachable 64 65 // 沒有網絡 66 // [wifi currentReachabilityStatus] == NotReachable 67 // [conn currentReachabilityStatus] == NotReachable