前置準備
- 專案加入
SystemConfiguration.framework。
- 匯入
Reachability.h(若使用 ASIHTTPRequest 直接引用其內建類別)。
核心檢測方法
- (BOOL)isConnectionAvailable {
BOOL isExistenceNetwork = YES;
Reachability *reach = [Reachability reachabilityWithHostName:@""];
switch ([reach currentReachabilityStatus]) {
case NotReachable:
isExistenceNetwork = NO;
break;
case ReachableViaWiFi:
case ReachableViaWWAN:
isExistenceNetwork = YES;
break;
}
if (!isExistenceNetwork) {
// 彈出提示(此處用 MBProgressHUD,可替換為 UIAlertController)
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeText;
hud.labelText = NSLocalizedString(@"INFO_NetNoReachable", nil);
hud.minSize = CGSizeMake(132.f, 108.f);
[hud hide:YES afterDelay:3];
return NO;
}
return isExistenceNetwork;
}
進階用法:區分 WiFi 與蜂窩網路
- (BOOL)isWiFiEnabled {
Reachability *reach = [Reachability reachabilityWithHostName:@""];
return [reach currentReachabilityStatus] == ReachableViaWiFi;
}
調用示例
if ([self isConnectionAvailable]) {
// 發起網路請求
} else {
// 提示用戶檢查網路
}

最佳實踐提醒
- 僅在發起網路請求前瞬間檢測,避免頻繁輪詢消耗電量。
- App Transport Security (ATS) 要求 HTTPS,請確保伺服器支援 TLS 1.2+。
- iOS 12+ 建議改用
NWPathMonitor 取代 Reachability,獲得更精準的網路路徑變更通知。