iOS開發(fā)網(wǎng)絡(luò)篇—監(jiān)測網(wǎng)絡(luò)狀態(tài)

一、說明

在網(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容