網路狀態判斷是幾乎每個 App 都需要的基礎功能:沒網路的時候要給提示、要暫停自動播放、要避免送出會失敗的請求。Apple 官方的 Reachability 類別是最省事的做法,網路上都能找到 Reachability.h 與 Reachability.m,拖進專案即可。
核心只有三件事:註冊通知、建立 Reachability 物件、啟動 notifier。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
// 初始化登入頁
LoginViewController *loginCtrl = [[LoginViewController alloc] init];
self.window.rootViewController = loginCtrl;
// 註冊網路狀態變更通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
[reach startNotifier]; // 開始監聽,這行不可省略
[self.window makeKeyAndVisible];
return YES;
}
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability *reach = [note object];
if ([reach isReachable]) {
NSLog(@"Notification Says Reachable");
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
message:@"網絡已斷開"
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alertView show];
NSLog(@"Notification Says Unreachable");
}
}
addObserverForName:object:queue:usingBlock:,並保存回傳的 token 以便移除。www.baidu.com,若該站台 DNS 出問題,你的判斷也會跟著出錯。建議改成 reachabilityForInternetConnection(監聽 0.0.0.0 路由)或自家服務的網域。