iOS 使用 Reachability 監聽網路狀態

黑暗森林的歌者發表於2018-02-26

為了適配 ipv6 ,原來使用的監聽是 AFN 自帶的,不知道為什麼在 ipv6 下監聽容易出現延遲甚至獲取狀態錯誤,於是使用 Reachability 這個框架

為了讓 APP 在執行中一直監聽,需要給 Appdelegate宣告一個 Reachability 屬性:

@property(nonatomic, strong) Reachability *reachability;
複製程式碼

didFinishLaunchingWithOptions方法中啟動監聽,使用通知收取網路狀態的變化:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[self.reachability startNotifier];
複製程式碼

監聽網路狀態回撥

- (void)reachabilityChanged:(NSNotification *)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:        {// 網路不能使用
           
            break;
        }
            
        case ReachableViaWWAN:        { // 使用的資料流量
            
            break;
        }
        case ReachableViaWiFi:        { // 使用的 WiFi
           
            break;
        }
    }
}
複製程式碼

Reachability 官方 Demo

相關文章