2.檢查網路狀態

夏雪冬日發表於2014-04-15

      以後慢慢啟用個人部落格:http://www.yuanrengu.com

  當應用程式需要訪問網路時,它首先應該檢查裝置的網路狀態,確認裝置的網路環境及連線情況,並針對這些情況提醒使用者做出相應的處理。最好能監聽裝置的網路狀態的改變,當裝置網路狀態連線、斷開時,程式也應該有相應的處理。

  工欲善其事必先利器,在檢查裝置的網路狀態前,我們要先實現兩個步驟:

  1. 下載,新增Reachability類。

    下載Reachability.zip壓縮包,最新的版本為V3.5,解壓該壓縮包會得到一個Xcode專案,其實關鍵是得到改專案的Reachability.h和 Reachability.m檔案,並把它們新增到專案中。

      2. 為專案新增SystemConfiguration.framework框架。

     新增方法:

  • 1)   選中專案名稱
  • 2)選中TARGETS
  • 3)選中Build Phases
  • 4)在Link Binary With Libraries中新增。

  

  將Reachability.h和 Reachability.m檔案新增到專案中。

  注意:如果Reachability不是3.0以上的版本,而是Reachability 2.x版本,它是不支援ARC的。本專案已經啟用了ARC,早期版本的Reachability類並不支援ARC,因此需要手動設定該類禁用ARC。

  開啟Main.storyboard介面設計檔案,向該檔案中新增1個UILabel,1個UITextFieldhe 3個UIButton,如下圖所示(^_^不好意思,最下面2個UILabel是打廣告的)。為了在程式中訪問介面上的文字框,將文字框繫結到siteField IBOutlet屬性。為了讓程式能相應介面上3個按鈕的點選事件,將“測試”按鈕的“Touch UP Inside”事件繫結testNetStatus:事件處理方法,為“測試WIFI”按鈕的“Touch UP Inside”事件繫結testWifi:事件處理方法,為“測試3G/4G”按鈕的“Touch UP Inside”事件繫結testInternet:事件處理方法。

  

 

  接下來編輯該示例的檢視控制器類,該檢視控制器類的實現部分主要依靠Reachability類來檢測網路狀態。

  核心實現程式碼:

 

 1 //  ViewController.m
 2 //  NetWorkDemo
 3 //
 4 //  Copyright (c) 2014年 MiracleHe. All rights reserved.
 5 //
 6 
 7 #import "ViewController.h"
 8 #import "Reachability.h"
 9 
10 @interface ViewController ()
11 
12 @end
13 
14 @implementation ViewController
15 @synthesize siteField;
16 
17 - (void)viewDidLoad
18 {
19     [super viewDidLoad];
20     // Do any additional setup after loading the view, typically from a nib.
21 }
22 - (IBAction)testNetStatus:(id)sender {
23     NSString *site = self.siteField.text;
24     Reachability *reach = [Reachability reachabilityWithHostName: site];
25     switch ([reach currentReachabilityStatus]) {
26         case NotReachable:
27             [self showAlert:[NSString stringWithFormat:@"不能訪問%@", site]];
28             break;
29         
30         case ReachableViaWWAN:
31             [self showAlert:[NSString stringWithFormat:@"使用3G/4G網路訪問%@", site]];
32             break;
33             
34         case ReachableViaWiFi:
35             [self showAlert:[NSString stringWithFormat:@"使用Wifi網路訪問%@", site]];
36             break;
37     }
38     
39 }
40 
41 
42 - (IBAction)testWifi:(id)sender {
43     if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable) {
44         [self showAlert:@"wifi網路已經連線"];
45     }else{
46         [self showAlert:@"wifi網路不可用。"];
47     }
48 }
49 
50 
51 - (IBAction)testInternet:(id)sender {
52     if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) {
53         [self showAlert:@"3G/4G網路已經連線"];
54     }else{
55         [self showAlert:@"3G/4G網路不可用"];
56     }
57 }
58 
59 -(void) showAlert:(NSString*) msg
60 {
61     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路狀態" message:msg delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
62     [alert show];
63     
64 }
65 
66 -(BOOL)textFieldShouldReturn:(UITextField *)textField
67 {
68     [siteField resignFirstResponder];
69     return YES;
70     
71 }
72 
73 - (void)didReceiveMemoryWarning
74 {
75     [super didReceiveMemoryWarning];
76     // Dispose of any resources that can be recreated.
77 }
78 
79 @end

 

  上面程式首先呼叫了Reachability類的reachabilityWithHostName:類方法來獲取Reachability物件,然後呼叫該物件的currentReachabilityStatus方法來獲取訪問指定站點的方式,該方法返回NetworkStatus列舉值,該列舉值有如下3個:

typedef enum{
    NotReachable = 0,     //無連線
    ReachableViaWiFi,     //使用3G/4G網路
    ReachableViaWWAN      //使用WiFi網路
}NetworkStatus;

  上面程式對Reachability的currentReachabilityStatus方法返回值進行判斷,這樣即可獲取該應用訪問網路的狀態和方式。

  編譯、執行該程式,如對www.cnblogs.com進行“測試”,效果如下圖。

  如果訪問的站點本身不存在,即時裝置的網路處於連線狀態,Reachability物件的currentReachabilityStatus方法也將返回NotReachable。

  如果程式僅需要測試裝置的WiFi或3G/4G網路是否連線,則可先呼叫Reachability類的reachabilityForLocalWiFi或reachabilityForInternetConnection類方法獲取Reachability物件,然後呼叫該Reachability物件的currentReachabilityStatus方法獲取網路連線狀態,如果網路連線狀態返回NotReachable,則表明這種型別的網路暫未連線。

 

  除了直接檢測網路連線狀態之外,有時候程式還需要監聽網路狀態的改變。當網路斷開連線時,提醒使用者,網路連線已經斷開,應用可能需要暫停;當網路重新連線時,再次提醒使用者,應用可以繼續執行。程式獲取Reachability物件之後,呼叫Reachability物件的startNotifier方法即可開啟該物件的被監聽狀態——當Reachability的連線狀態發生改變時,該物件將會傳送一個kReachabilityChangedNotification通知給預設的通知中心,因此程式只要使用預設的通知中心監聽該通知即可。

  為了監聽網路狀態的改變,在應用程式委託類(AppDelegate.m)的application: didFinishLaunchingWithOptions:方法中增加如下程式碼:

    //使用通知中心監聽kReachabilityChangedNotification通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //獲取訪問指定站點的Reachability物件
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.cnblogs.com"];
    //讓Reachability物件開啟被監聽狀態
    [reach startNotifier];

  上面的程式碼使用預設的通知中心檢測kReachabilityChangedNotification通知,這意味著當Reachability的連線狀態發生改變時,預設的通知中心就會收到該通知,從而觸發應用程式委託類的reachabilityChanged:方法,還需要在應用程式委託類中定義如下方法:

- (void) reachabilityChanged:(NSNotification*) note
{
    //通過通知物件獲取被監聽的Reachability物件
    Reachability *curReach = [note object];
    //獲取Reachability物件的網路狀態
    NetworkStatus status = [curReach currentReachabilityStatus];
    if (status == NotReachable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"不能訪問www.cnblogs.com" delegate:nil cancelButtonTitle:@"YES" otherButtonTitles: nil];
        [alert show];
    }
}

   reachabilityChanged:會判斷該Reachability物件的網路連線狀態,當該物件的網路連線狀態處於NotReachable時,程式會使用UIAlertView進行提醒。 

   希望上面的總結能對正在學習iOS開發的小夥伴有一點點幫助,假如覺得還不錯,煩請小夥伴不要忘記右下角的點“推薦”哦!

 

相關文章