您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

Reachability 檢查網路狀態的正確用法與常見誤解

編輯:iOS 相關資訊

Reachability 是蘋果官方提供的網路狀態偵測工具,幾乎每個需要連網的 App 都會用它。但它常被誤用,這裡記錄一次實際踩雷的經驗與正確的使用方式。

一個容易誤解的情況

情境是這樣的:裝置連上了 Wi-Fi,實際上卻無法上網。此時用 Reachability 檢查,它會告訴你「處於 Wi-Fi 環境」——這其實沒錯,它確實只是回報連線類型。但若因此就認為可以正常取網路資料,請求就會卡住直到逾時,而預設逾時時間往往長達 15 秒,對使用者體驗是種傷害。

仔細研究後可以發現,Reachability 判斷網路類型的方式相當簡單:只檢查有沒有 IP 位址。所以它天生就無法分辨「連得上卻不通」的情況。這不是 bug,而是設計定位不同。

如何避開逾時卡住的問題

若使用 ASIHTTPRequest 發請求,可以設定逾時時間:[request setTimeOutSeconds:5];。若使用 NSURLRequest,則可忽略本地快取並設定逾時:

NSURLRequest *request = [NSURLRequest requestWithURL:url1
                                         cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                     timeoutInterval:10];

一種直接驗證連通性的做法

NSURL *url1 = [NSURL URLWithString:@"https://www.51ios.net/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url1
                                         cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                     timeoutInterval:10];
NSCachedURLResponse *response;
[NSURLConnection sendSynchronousRequest:request
                           returningResponse:&response
                                       error:nil];
if (response == nil) {
    NSLog(@"沒有網絡");
} else {
    NSLog(@"網絡是通的");
}

原理很直觀:發一個請求並設定逾時,再依回應判斷連線是否真的可用。有兩點要注意:請求的位址最好就是你要存取的服務,回應內容也應該盡量簡單;另外這段程式若放在主執行緒執行,一樣會讓介面卡住,記得放到背景佇列。

所以說 Reachability 並沒有錯,錯的是把「判斷連線類型」的工具拿來「判斷連通性」。把對的工具用在對的地方,才是關鍵。

以通知機制即時監聽網路變化

// 在程式啟動處開啟監聽
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(reachabilityChanged:)
                                                name:kReachabilityChangedNotification
                                              object:nil];

    hostReach = [[Reachability reachabilityWithHostName:@"https://www.51ios.net/"] retain];
    [hostReach startNotifier];  // 開始監聽,會啟動一個 run loop
    [self updateInterfaceWithReachability:hostReach];
    return YES;
}

// 連線狀態改變
- (void)reachabilityChanged:(NSNotification *)note {
    Reachability *curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

// 依狀態更新介面
- (void)updateInterfaceWithReachability:(Reachability *)curReach {
    NetworkStatus status = [curReach currentReachabilityStatus];
    if (status == NotReachable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App Name"
                                                       message:@"NotReachable"
                                                      delegate:nil
                                             cancelButtonTitle:@"YES"
                                             otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

重點小結

Reachability 適合用來「監聽網路條件的變化並即時更新 UI」,例如無網路時提示使用者;但要確認「這個請求到底通不通」,還是得靠實際請求加上合理的逾時設定。兩者搭配使用,才能兼顧準確性與使用者體驗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved