有些 App 只在 WiFi 下提供完整功能(例如 Reeder 的高畫質圖片),有些則需要在無網路時提供離線模式(例如 Evernote)。這類需求都會用到 Reachability 這個函式庫。
Reachability 是 iOS 上用來偵測裝置網路環境的函式庫,可以:監視特定主機是否可達、判斷目前的連線方式、以及接收連線方式變更的通知。
Apple 官方文件與範例:https://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
社群版本(tonymillion):https://github.com/tonymillion/Reachability
SystemConfiguration.framework由於 Reachability 使用頻率很高,可以直接加入 Supporting Files 中的 prefix pch 檔,省去每個檔案手動引入的麻煩。
- (void)viewDidLoad {
[super viewDidLoad];
DLog(@"開啟 www.apple.com 的網路偵測");
Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
DLog(@"-- current status: %@", reach.currentReachabilityString);
// 啟動 notifier,這會讓 reachability 物件自我 retain
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
[reach startNotifier];
}
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *reach = [note object];
if (![reach isReachable]) {
self.notificationLabel.text = @"網路不可用";
self.notificationLabel.backgroundColor = [UIColor redColor];
self.wifiOnlyLabel.backgroundColor = [UIColor redColor];
self.wwanOnlyLabel.backgroundColor = [UIColor redColor];
return;
}
self.notificationLabel.text = @"網路可用";
self.notificationLabel.backgroundColor = [UIColor greenColor];
if (reach.isReachableViaWiFi) {
self.wifiOnlyLabel.backgroundColor = [UIColor greenColor];
self.wifiOnlyLabel.text = @"當前通過 wifi 連接";
} else {
self.wifiOnlyLabel.backgroundColor = [UIColor redColor];
self.wifiOnlyLabel.text = @"wifi 未開啟,不能用";
}
if (reach.isReachableViaWWAN) {
self.wwanOnlyLabel.backgroundColor = [UIColor greenColor];
self.wwanOnlyLabel.text = @"當前通過 2g or 3g 連接";
} else {
self.wwanOnlyLabel.backgroundColor = [UIColor redColor];
self.wwanOnlyLabel.text = @"2g or 3g 網路未使用";
}
}
WiFi 開啟狀態:

WiFi 關閉狀態:

[[NSNotificationCenter defaultCenter] removeObserver:self],並對 Reachability 呼叫 stopNotifier。reachabilityWithHostname: 指定的主機若被阻擋或 DNS 異常,結果可能與實際連線能力不一致,重要操作仍應搭配實際請求的失敗回呼來處理。NWPathMonitor(Network framework)取代 Reachability,API 更現代且不需引入第三方庫。