iOS編程-網路監測

來源:互聯網
上載者:User

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(@沒有網路);

}

}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.