網路應用有必要隨時掌握使用者的連線狀態,原因有兩個:一是讓使用者明白「現在是網路問題,不是 App 壞了」;二是依連線品質做聰明決策,替使用者省流量。
典型的策略是:WIFI 環境下載高清圖,行動網路只抓縮圖,完全沒有網路時就顯示離線快取內容。
蘋果官方提供了 Reachability 這個範例程式,是偵測網路狀態最省事的方式:
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
步驟三項:
1. 加入框架 SystemConfiguration.framework。

2. 加入原始碼 Reachability.h 與 Reachability.m。

3. 引入標頭
#import "Reachability.h"
// NetworkTool.h
@interface NetworkTool : NSObject
+ (BOOL)isEnableWIFI;
+ (BOOL)isEnable3G;
@end
// NetworkTool.m
#import "NetworkTool.h"
#import "Reachability.h"
@implementation NetworkTool
+ (BOOL)isEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
+ (BOOL)isEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
@end
若要即時反應網路切換,則需註冊通知並啟動 notifier:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
self.netReachability = [Reachability reachabilityForInternetConnection];
[self.netReachability startNotifier];
}
- (void)dealloc {
[self.netReachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:kReachabilityChangedNotification
object:nil];
}
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkStateChange)
name:kReachabilityChangedNotification
object:nil];
self.reachability = [Reachability reachabilityForInternetConnection];
[self.reachability startNotifier];
}
- (void)dealloc {
[self.reachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self checkNetworkState];
}
#pragma mark - 網路類型改變時呼叫
- (void)networkStateChange {
if ([NetworkTool isEnableWIFI]) {
[[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
message:@"您現在的網路環境為 WIFI!開始暢享吧!"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil] show];
} else if ([NetworkTool isEnable3G]) {
[[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
message:@"您現在的網路環境為 3G/4G!"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil] show];
} else {
[[[UIAlertView alloc] initWithTitle:@"溫馨提示您"
message:@"您目前沒有可連的網路或已經離線!"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil] show];
}
}
@end
Reachability 判斷的是「有沒有可達的路徑」,而不是「網路品質好不好」。使用者連上咖啡廳 WIFI 但沒有對外網路時,reachabilityForLocalWiFi 仍會回報可達,因此關鍵請求還是要靠 timeout 與失敗重試來把關。
另外,Reachability 已被官方標記為 deprecated,新專案建議改用 NWPathMonitor(Network 框架)。它只需要幾行就能完成同樣的事,而且能同時取得介面型別(WIFI/蜂巢式/有線)與串流狀態:
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// 依 path.usesInterfaceType(.wifi) 判斷連線方式
}
}
monitor.start(queue: DispatchQueue(label: "NetworkMonitor"))
最後,網路狀態變化的通知可能來得相當頻繁(例如行動網路在基地台間切換)。若每收到一次通知就跳提示框,使用者會被洗版。實務上應加上 debounce 或只在「狀態等級真正改變」時才更新 UI。