[英]How to get notified when wifi gets connected or disconnected in iOS?
I'm trying to get iOS to notify my app when a wifi connection is either established or disconnected. 我正在尝试让iOS在建立或断开wifi连接时通知我的应用程序。
I tried the following code in iPhone and iPad with iOS 4.3.5 and 5.1: 我在带有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");
}
}
The problem is that my callback "statusUpdated" never gets called. 问题是我的回调“ statusUpdated”从未被调用过。 I know this SHOULD work as is, but I tried both getting in and out of the wifi range (and therefore getting connected and disconnected to it) and turning on and off the wifi router to force disconnection and my callback is never called.
我知道应该按原样工作,但是我尝试进入和退出wifi范围(并因此与之建立连接和断开连接)并打开和关闭wifi路由器以强制断开连接,并且从未调用我的回调。
I also tried this: 我也试过这个:
@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];
}
and tested it under the same scenarios and it works fine. 并在相同的场景下对其进行了测试,并且效果很好。 However that's not the approach I need, I rather need notifications to invoke my callback.
但这不是我需要的方法,我需要通知来调用我的回调。
Is there anything else I have to do to make the notifier work? 为了使通知程序正常工作,我还有其他事情要做吗?
Use this library http://huytd.github.io/datatify/ it's very easy to use and to customize. 使用此库http://huytd.github.io/datatify/,它非常易于使用和自定义。 The setCallback method will help you detect when the connection changed
setCallback方法将帮助您检测连接何时更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.