App 在發請求前先確認網路是否可用,能避免大量無效的超時等待,也能給使用者更明確的錯誤提示。以下分成「主動查詢」與「被動監聽」兩部分。
做法是以 0.0.0.0 這個零地址建立 reachability 參考,讀取系統的連線旗標。
- (int)connectedToNetwork {
// 零地址代表查詢本機的網路連線狀態
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef defaultRouteReachability =
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
return -1; // 無法取得旗標
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
if (isReachable && !needsConnection) {
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
return 0; // 行動網路
}
return 1; // Wi-Fi
}
return -1; // 無法連線
}
這裡的關鍵是兩個旗標的組合:kSCNetworkFlagsReachable 表示「路由可達」,kSCNetworkFlagsConnectionRequired 表示「需要額外建立連線(例如需要 Portal 認證)」。兩者同時成立才算真正可用。
- (void)SetJianCeNetwork {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
hostReach = [[Reachability reachabilityWithHostname:@"www.example.com"] retain];
[hostReach startNotifier]; // 啟動監聽,會跑一個 run loop
}
- (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:nil
message:@"網路連線失敗,請檢查網路設定"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
if (status == ReachableViaWiFi || status == ReachableViaWWAN) {
// 網路可用,可以啟動背景執行緒做進一步的資料驗證
NSThread *initThread = [[NSThread alloc] initWithTarget:self
selector:@selector(initThreadFunc:)
object:self];
[initThread start];
}
}
- (void)initThreadFunc:(id)sender {
if ([g_json Test]) {
[g_json UserLogin:0 pass:nil];
[self GetUpdate];
}
}
可達不等於網路可用。 Reachability 只能告訴你「有網路介面」,並不代表能連上網際網路。飯店、機場常見的 Captive Portal 會讓 Wi-Fi 顯示為可達,但實際請求全部失敗。因此除了監聽 reachability,還應該對關鍵 API 做「連得上嗎」的實際探測。
記得移除 observer。 在 dealloc 中呼叫 [[NSNotificationCenter defaultCenter] removeObserver:self],否則通知觸發時會指向已釋放的物件。
Reachability 已不再維護。 Apple 自家的 Reachability 範例專案多年未更新。新專案建議改用 NWPathMonitor(iOS 12 以後),API 更簡潔且以 block 回呼:
NWPathMonitor *monitor = [[NWPathMonitor alloc] init];
monitor.pathUpdateHandler = ^(NWPath *path) {
if (path.status == NWPathStatusSatisfied) {
// 網路可用
}
};
[monitor startWithQueue:dispatch_get_global_queue(0, 0)];