當應(yīng)用程序需要訪問網(wǎng)絡(luò)時,它首先應(yīng)該檢查設(shè)備的網(wǎng)絡(luò)狀態(tài),確認設(shè)備的網(wǎng)絡(luò)環(huán)境及連接情況,并針對這些情況提醒用戶做出相應(yīng)的處理。最好能監(jiān)聽設(shè)備的網(wǎng)絡(luò)狀態(tài)的改變,當設(shè)備網(wǎng)絡(luò)狀態(tài)連接、斷開時,程序也應(yīng)該有相應(yīng)的處理。
工欲善其事必先利器,在檢查設(shè)備的網(wǎng)絡(luò)狀態(tài)前,我們要先實現(xiàn)兩個步驟:
下載Reachability.zip壓縮包,最新的版本為V3.5,解壓該壓縮包會得到一個Xcode項目,其實關(guān)鍵是得到改項目的Reachability.h和 Reachability.m文件,并把它們添加到項目中。

2. 為項目添加SystemConfiguration.framework框架。
添加方法:

將Reachability.h和 Reachability.m文件添加到項目中。
注意:如果Reachability不是3.0以上的版本,而是Reachability 2.x版本,它是不支持ARC的。本項目已經(jīng)啟用了ARC,早期版本的Reachability類并不支持ARC,因此需要手動設(shè)置該類禁用ARC。
打開Main.storyboard界面設(shè)計文件,向該文件中添加1個UILabel,1個UITextFieldhe 3個UIButton,如下圖所示(^_^不好意思,最下面2個UILabel是打廣告的)。為了在程序中訪問界面上的文本框,將文本框綁定到siteField IBOutlet屬性。為了讓程序能相應(yīng)界面上3個按鈕的點擊事件,將“測試”按鈕的“Touch UP Inside”事件綁定testNetStatus:事件處理方法,為“測試WIFI”按鈕的“Touch UP Inside”事件綁定testWifi:事件處理方法,為“測試3G/4G”按鈕的“Touch UP Inside”事件綁定testInternet:事件處理方法。

接下來編輯該示例的視圖控制器類,該視圖控制器類的實現(xiàn)部分主要依靠Reachability類來檢測網(wǎng)絡(luò)狀態(tài)。
核心實現(xiàn)代碼:
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 @end13 14 @implementation ViewController15 @synthesize siteField;16 17 - (void)viewDidLoad18 {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網(wǎng)絡(luò)訪問%@", site]];32 break;33 34 case ReachableViaWiFi:35 [self showAlert:[NSString stringWithFormat:@"使用Wifi網(wǎng)絡(luò)訪問%@", site]];36 break;37 }38 39 }40 41 42 - (IBAction)testWifi:(id)sender {43 if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable) {44 [self showAlert:@"wifi網(wǎng)絡(luò)已經(jīng)連接"];45 }else{46 [self showAlert:@"wifi網(wǎng)絡(luò)不可用。"];47 }48 }49 50 51 - (IBAction)testInternet:(id)sender {52 if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) {53 [self showAlert:@"3G/4G網(wǎng)絡(luò)已經(jīng)連接"];54 }else{55 [self showAlert:@"3G/4G網(wǎng)絡(luò)不可用"];56 }57 }58 59 -(void) showAlert:(NSString*) msg60 {61 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)狀態(tài)" message:msg delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];62 [alert show];63 64 }65 66 -(BOOL)textFieldShouldReturn:(UITextField *)textField67 {68 [siteField resignFirstResponder];69 return YES;70 71 }72 73 - (void)didReceiveMemoryWarning74 {75 [super didReceiveMemoryWarning];76 // Dispose of any resources that can be recreated.77 }78 79 @end
上面程序首先調(diào)用了Reachability類的reachabilityWithHostName:類方法來獲取Reachability對象,然后調(diào)用該對象的currentReachabilityStatus方法來獲取訪問指定站點的方式,該方法返回NetworkStatus枚舉值,該枚舉值有如下3個:
typedef enum{ NotReachable = 0, //無連接 ReachableViaWiFi, //使用3G/4G網(wǎng)絡(luò) ReachableViaWWAN //使用WiFi網(wǎng)絡(luò)}NetworkStatus;
上面程序?qū)eachability的currentReachabilityStatus方法返回值進行判斷,這樣即可獲取該應(yīng)用訪問網(wǎng)絡(luò)的狀態(tài)和方式。
編譯、運行該程序,如對m.survivalescaperooms.com進行“測試”,效果如下圖。

如果訪問的站點本身不存在,即時設(shè)備的網(wǎng)絡(luò)處于連接狀態(tài),Reachability對象的currentReachabilityStatus方法也將返回NotReachable。
如果程序僅需要測試設(shè)備的WiFi或3G/4G網(wǎng)絡(luò)是否連接,則可先調(diào)用Reachability類的reachabilityForLocalWiFi或reachabilityForInternetConnection類方法獲取Reachability對象,然后調(diào)用該Reachability對象的currentReachabilityStatus方法獲取網(wǎng)絡(luò)連接狀態(tài),如果網(wǎng)絡(luò)連接狀態(tài)返回NotReachable,則表明這種類型的網(wǎng)絡(luò)暫未連接。
除了直接檢測網(wǎng)絡(luò)連接狀態(tài)之外,有時候程序還需要監(jiān)聽網(wǎng)絡(luò)狀態(tài)的改變。當網(wǎng)絡(luò)斷開連接時,提醒用戶,網(wǎng)絡(luò)連接已經(jīng)斷開,應(yīng)用可能需要暫停;當網(wǎng)絡(luò)重新連接時,再次提醒用戶,應(yīng)用可以繼續(xù)運行。程序獲取Reachability對象之后,調(diào)用Reachability對象的startNotifier方法即可開啟該對象的被監(jiān)聽狀態(tài)——當Reachability的連接狀態(tài)發(fā)生改變時,該對象將會發(fā)送一個kReachabilityChangedNotification通知給默認的通知中心,因此程序只要使用默認的通知中心監(jiān)聽該通知即可。
為了監(jiān)聽網(wǎng)絡(luò)狀態(tài)的改變,在應(yīng)用程序委托類(AppDelegate.m)的application: didFinishLaunchingWithOptions:方法中增加如下代碼:
//使用通知中心監(jiān)聽kReachabilityChangedNotification通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; //獲取訪問指定站點的Reachability對象 Reachability *reach = [Reachability reachabilityWithHostName:@"m.survivalescaperooms.com"]; //讓Reachability對象開啟被監(jiān)聽狀態(tài) [reach startNotifier];
上面的代碼使用默認的通知中心檢測kReachabilityChangedNotification通知,這意味著當Reachability的連接狀態(tài)發(fā)生改變時,默認的通知中心就會收到該通知,從而觸發(fā)應(yīng)用程序委托類的reachabilityChanged:方法,還需要在應(yīng)用程序委托類中定義如下方法:
- (void) reachabilityChanged:(NSNotification*) note{ //通過通知對象獲取被監(jiān)聽的Reachability對象 Reachability *curReach = [note object]; //獲取Reachability對象的網(wǎng)絡(luò)狀態(tài) NetworkStatus status = [curReach currentReachabilityStatus]; if (status == NotReachable) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"不能訪問m.survivalescaperooms.com" delegate:nil cancelButtonTitle:@"YES" otherButtonTitles: nil]; [alert show]; }}
reachabilityChanged:會判斷該Reachability對象的網(wǎng)絡(luò)連接狀態(tài),當該對象的網(wǎng)絡(luò)連接狀態(tài)處于NotReachable時,程序會使用UIAlertView進行提醒。
希望上面的總結(jié)能對正在學(xué)習(xí)iOS開發(fā)的小伙伴有一點點幫助,假如覺得還不錯,煩請小伙伴不要忘記右下角的點“推薦”哦!
新聞熱點
疑難解答