天天看點

用Reachability實時監聽網絡的變化

didFinishLaunchingWithOptions中增加如下代碼

 //使用通知中心監聽kReachabilityChangedNotification通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    //擷取指定站點的Reachability對象

    reach=[Reachability reachabilityWithHostName:@"www.baidu.com"];

    //讓Reachability對象開啟被監聽狀态

    [reach startNotifier];

-(void)reachabilityChanged:(NSNotification *)note

{

    NSLog(@"進來了");

    //通過通知對象擷取被監聽的Reachability對象

    Reachability *currReach=[note object];

    //擷取Reachability對象的網絡狀态

    NetworkStatus status=[currReach currentReachabilityStatus];

    if (status==NotReachable) {

        [self showAlert:@"www.baidu.com"];

    }else{

        [self showAlert:@"網絡正常"];

    }

}

我做這塊遇到的問題就是一開始通知無論怎麼都不執行,從網上看了才知道

Reachability *reach要設定為全局對象,我認為不把它設定為全局對象,它可能出了該函數就被系統釋放了!!!

繼續閱讀