iOS編程-網路監測
在網路應用中,需要對使用者裝置的網路狀態進行即時監控,有兩個目的:
(1)讓使用者瞭解自己的網路狀態,防止一些誤會(比如怪應用無能)
(2)根據使用者的網路狀態進行智能處理,節省使用者流量,提高使用者體驗
WIFIG網路:自動下載高清圖片
低速網路:只下載縮圖
沒有網路:只顯示離線的快取資料
蘋果官方提供了一個叫Reachability的樣本程式,便於開發人員檢測網路狀態
www.bkjia.com
二、監測網路狀態
Reachability的使用步驟
添加架構SystemConfiguration.framework
添加原始碼
包含標頭檔
#import Reachability.h
#import QYViewController.h
#import Reachability.h
@interface QYViewController ()
@property (nonatomic, strong) Reachability *conn;
@end
@implementation QYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[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)checkNetworkState
{
// 1.檢測wifi狀態
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.檢測手機是否能上網路(WIFIG.5G)
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判斷網路狀態
if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
NSLog(@有wifi);
} else if ([conn currentReachabilityStatus] != NotReachable) { // 沒有使用wifi, 使用手機內建網路進行上網
NSLog(@使用手機內建網路進行上網);
} else { // 沒有網路
NSLog(@沒有網路);
}
}