簡體   English   中英

在iOS中連接或斷開wifi時如何獲取通知?

[英]How to get notified when wifi gets connected or disconnected in iOS?

我正在嘗試讓iOS在建立或斷開wifi連接時通知我的應用程序。

我在帶有iOS 4.3.5和5.1的iPhone和iPad中嘗試了以下代碼:

- (void)startWifiNotifier {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(statusUpdated:) 
                                                 name:kReachabilityChangedNotification 
                                               object:nil];

    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    [wifi startNotifier];
    NSLog(@"Wifi status: %i", [wifi currentReachabilityStatus]);
    NSLog(@"Notifier started");
}

- (void)statusUpdated:(NSNotification *)notice {
    NetworkStatus s = [[notice object] currentReachabilityStatus];
    if(s == NotReachable) {
        NSLog(@"Wifi disconnected");
    } else {
        NSLog(@"Wifi connection established");
    }
}

問題是我的回調“ statusUpdated”從未被調用過。 我知道應該按原樣工作,但是我嘗試進入和退出wifi范圍(並因此與之建立連接和斷開連接)並打開和關閉wifi路由器以強制斷開連接,並且從未調用我的回調。

我也試過這個:

@private
    Reachability *wifi;
...

- (void) startTimerLog {
   wifi = [Reachability reachabilityForLocalWiFi];
   [self timerLog];
}

- (void) timerLog {
    NSLog(@"Reachability: %i", [wifi currentReachabilityStatus]);
    [self performSelector:@selector(timerLog) withObject:nil afterDelay:0.5];    
}

並在相同的場景下對其進行了測試,並且效果很好。 但這不是我需要的方法,我需要通知來調用我的回調。

為了使通知程序正常工作,我還有其他事情要做嗎?

使用此庫http://huytd.github.io/datatify/,它非常易於使用和自定義。 setCallback方法將幫助您檢測連接何時更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM