標籤:oc 網路應用 網路 編程
在網路應用中,需要對使用者裝置的網路狀態進行即時監控,有兩個目的:
(1)讓使用者瞭解自己的網路狀態,防止一些誤會(比如怪應用無能)
(2)根據使用者的網路狀態進行智能處理,節省使用者流量,提高使用者體驗
WIFI\3G網路:自動下載高清圖片
低速網路:只下載縮圖
沒有網路:只顯示離線的快取資料
蘋果官方提供了一個叫Reachability的樣本程式,便於開發人員檢測網路狀態
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
二、監測網路狀態
Reachability的使用步驟
添加架構SystemConfiguration.framework
添加原始碼
包含標頭檔
#import "Reachability.h"
#import "QYViewController.h"
#import "Reachability.h"
@interface QYViewController ()
@property (nonatomic,strong) Reachability *conn;
@end
@implementation QYViewController
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(networkStateChange)name:kReachabilityChangedNotificationobject:nil];
self.conn = [ReachabilityreachabilityForInternetConnection];
[self.connstartNotifier];
}
- (void)dealloc
{
[self.connstopNotifier];
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
- (void)networkStateChange
{
[selfcheckNetworkState];
}
- (void)checkNetworkState
{
// 1.檢測wifi狀態
Reachability *wifi = [ReachabilityreachabilityForLocalWiFi];
// 2.檢測手機是否能上網路(WIFI\3G\2.5G)
Reachability *conn = [ReachabilityreachabilityForInternetConnection];
// 3.判斷網路狀態
if ([wificurrentReachabilityStatus] != NotReachable) {// 有wifi
NSLog(@"有wifi");
} elseif ([conn currentReachabilityStatus] != NotReachable) {// 沒有使用wifi,使用手機內建網路進行上網
NSLog(@"使用手機內建網路進行上網");
}else { // 沒有網路
NSLog(@"沒有網路");
}
}
iOS編程-網路監測