Reachability 實(shí)時(shí)監(jiān)控網(wǎng)絡(luò)狀態(tài)

  • 從官網(wǎng)出下載Reachability.h/m文件,拖入工程

  • 調(diào)用Reachability.h頭文件,并創(chuàng)建全局變量Reachability *internetReachability;

  • 在AppDelegate的- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions方法中創(chuàng)建通知

 //添加一個(gè)系統(tǒng)通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //初始化
    internetReachability=[Reachability reachabilityForInternetConnection];
    //通知添加到Run Loop
    [internetReachability startNotifier];
    [self updateInterfaceWithReachability:internetReachability];
  • 實(shí)現(xiàn)通知方法
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}
  • 監(jiān)測(cè)網(wǎng)絡(luò)狀態(tài)方法
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
    switch (netStatus) {
        case NotReachable:
            NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)不可用=======");
            break;
        case ReachableViaWiFi:
            NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)為Wifi=======");
            break;
        case ReachableViaWWAN:
            NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)為流量=======keso");
            break;
    }
}

注:

  • 此方法能監(jiān)測(cè)所有頁(yè)面的網(wǎng)絡(luò)狀態(tài),可是要在當(dāng)前頁(yè)面獲取當(dāng)前網(wǎng)絡(luò)狀態(tài)則需要使用AFNetWorking,如果不嫌麻煩那就一個(gè)一個(gè)寫.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容