Reachability 是蘋果官方提供的網絡狀態檢查庫,幾乎每個基於網絡的應用都會用它來判斷網絡。然而我在使用過程中,卻發現它存在一個容易誤判的陷阱,以下把經驗分享出來。
遇到的情況是:裝置連上了 Wi-Fi,但實際上並不能上網。此時用 Reachability 檢查,它會認為裝置處在 Wi-Fi 環境下(確實是連著 Wi-Fi)。如果這時理所當然地認為可以正常上網而直接去抓資料,就會一直等到請求逾時——而預設逾時時間似乎長達 15 秒,對使用者體驗是無法接受的。
仔細研究後發現,Reachability 在區分網絡連線類型時,其實只是簡單地檢查有沒有 IP 位址。這就難怪會出現「以為是 Wi-Fi 卻上不了網」的情況了。
如果用 ASIHTTPRequest 發送請求,可以設定逾時時間在一定程度上避開問題:
[request setTimeOutSeconds:5];
如果用 NSURLRequest,則可以用忽略本地快取並加上逾時的方式:
NSURLRequest *request = [NSURLRequest requestWithURL:url1
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
由此我想到一個判斷網絡是否真正連通的方法:發送一個網絡請求並設定逾時,再根據回傳結果判斷:
NSURL *url1 = [NSURL URLWithString:@"https://blog.cnrainbird.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url1
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
NSHTTPURLResponse *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:@"www.google.com"] 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];
}
}
透過 kReachabilityChangedNotification 通知,就能即時掌握網絡狀態的變化並做出相應處理。