網路應用裡監控使用者的連線狀態有兩個實際目的:一是讓使用者知道目前處於什麼網路環境,避免把問題誤判成 App 故障;二是依狀態做智能處理,節省流量並提升體驗。
典型的策略是:
Apple 官方提供了 Reachability 這支範例程式,專門用來偵測網路狀態。
第一步:加入 SystemConfiguration.framework

第二步:把 Reachability 的原始碼加進專案

第三步:引入標頭檔並監聽通知
#import "QYViewController.h"
#import "Reachability.h"
@interface QYViewController ()
@property (nonatomic, strong) Reachability *conn;
@end
@implementation QYViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkStateChange)
name:kReachabilityChangedNotification
object:nil];
self.conn = [Reachability reachabilityForInternetConnection];
[self.conn startNotifier];
}
- (void)dealloc {
[self.conn stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)networkStateChange {
[self checkNetworkState];
}
- (void)checkNetworkState {
// 1. 檢測 Wi-Fi 狀態
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2. 檢測是否能透過行動網路上網
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3. 判斷網路狀態
if ([wifi currentReachabilityStatus] != NotReachable) {
NSLog(@"有 Wi-Fi");
} else if ([conn currentReachabilityStatus] != NotReachable) {
NSLog(@"使用行動網路上網");
} else {
NSLog(@"沒有網路");
}
}
幾個使用上的提醒:
startNotifier 對應 stopNotifier,通知觀察者也必須成对移除,否則在 ARC 下容易造成野蠻的跨物件呼叫。NWPathMonitor(Network 框架)取代 Reachability,API 更簡潔且以 block / Combine 方式回報,新專案可以優先考慮。