iOS 檢測網路狀態

來源:互聯網
上載者:User

標籤:

1.為什麼要檢測網路狀態?

1.1 讓使用者知道自己的網路狀態,防止使用者埋怨"這個應用太垃圾,擷取資料那麼慢"

1.2 根據使用者的網路狀態,智能處理,提升使用者體驗

例如某些手機瀏覽器,檢測到使用者網路是2G/3G時,會自動切換為無圖模式

2.手動觸發

2.1 首先下載蘋果的樣本程式Reachability, 取得樣本程式裡的Reachability.h和Reachability.m, 添加到自己項目裡

代碼如下

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 檢測WIFI狀態

    Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

    // 檢測手機連網狀態(2G/3G/WIFI)

    Reachability *conn = [Reachability reachabilityForInternetConnection];

    

    if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

        NSLog(@"當前連著WIFI");

    }else{ //無WIFI

        if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G網路

            NSLog(@"當前連著2G/3G網路");

        }else{ //無2G/3G網路

            NSLog(@"當前沒連網");

        }

     }

}

 

2.2 實際應用中,不會讓使用者手動去檢測網路狀態,下面用通知實現即時檢測網路狀態

@property (nonatomic,strong) Reachability *coon;

   // 添加通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange) name:kReachabilityChangedNotification object:nil];

    self.coon = [Reachability reachabilityForInternetConnection];

    // 發送通知

    [self.coon startNotifier];

 

- (void)dealloc

{

    [self.coon stopNotifier];

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)networkChange

{

    [self checkNetworkState];

}

 

- (void)checkNetworkState

{

    Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

    Reachability *conn = [Reachability reachabilityForInternetConnection];

    if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

        NSLog(@"當前連著WIFI");

    }else{ //無WIFI

        if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G網路

            NSLog(@"當前連著2G/3G網路");

        }else{ //無2G/3G網路

            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.