我已经成功使用Reachability来检测网络状态并在发生更改时接收通知(例如:iOS 4下Reachability指南)。
我的问题不是如何启动和运行Reachability,而是以下内容:
我的AppDelegate
处理Reachability相关事宜。当应用程序正在运行或处于后台(applicationDidEnterBackground:
)时,应用程序会收到通知(kReachabilityChangedNotification
)。
该应用程序旨在在意识到失去Wi-Fi连接(例如测试时在设置中切换Wi-Fi),重新加载播放音频流。在实际测试中,当我离开访问点的范围时,经常失去Wi-Fi连接。我发现在这种情况下,Reachability并没有太大帮助。我不确定是因为当屏幕锁定时无法接收Reachability通知,还是Reachability无法处理从越来越远的Wi-Fi访问点慢慢减弱的信号,但无论如何,我都无法弄清楚为什么实际测试与理想化的情况不符。
这是我的代码样式。首先,我设置接收通知并开始监听Reachability:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification object:nil];
// Set up Reachability
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
....
return YES;
}
然后,这是响应连接变化的函数:
- (void)checkNetworkStatus:(NSNotification *)notice {
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN!");
break;
}
}
}
即使应用程序在后台运行,通知也会通过,但在上述的现实世界测试中没有收到。
感谢任何帮助。
reachabilityForInternetConnection
和reachabilityForLocalWifi
的组合吗? - Art Gillespie