iOS編程-網路監測

來源:互聯網
上載者:User

標籤: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編程-網路監測

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.