![](/img/trans.png)
[英]Reachability returns False for Cellular network when both Wi-Fi and Cellular is ON
[英]How to get Reachability Notifications in iOS in Background when dropping Wi-Fi network?
我正在成功使用Reachability来确定网络的状态,并获得有关更改的通知(例如iOS 4的可达性指南 )。
我的问题不是如何让Reachability启动和运行,而是如下。
我的AppDelegate
处理Reachability的东西。 应用程序运行时以及应用程序位于后台( applicationDidEnterBackground:
kReachabilityChangedNotification
时,应用程序会收到通知( kReachabilityChangedNotification
)。
该应用程序旨在重新加载播放的音频流,当它注意到它丢失了一个Wi-Fi连接,例如,为了测试,我在设置中打开和关闭Wi-Fi,一切都运行良好。 在实际测试中,当我退出接入点的范围时,我经常会失去Wi-Fi连接。 我发现在这种情况下,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;
}
}
}
即使应用程序处于后台,通知也会通过,但它们不在上述实际测试中。
谢谢你的帮助。
默认情况下,在后台状态应用程序仅停留一小段时间,大多数应用程序很快就会进入暂停状态。 这意味着应用程序在后台但不执行代码。 因此,您的自定义实施通知不起作用。 必须在应用程序委托方法中在唤醒时重新查询NetworkReachability:
applicationWillEnterForeground:
applicationDidBecomeActive
我正在开发一个VoIP应用程序,它在iPhone启动时在后台启动,此时可能没有网络可达性(例如,如果手机同时有密码和/或带有PIN码的SIM卡)。 但由于应用程序直接在后台启动,因此不会调用委托方法applicationDidEnterBackground:
. 相反,我所做的是直接在application:didFinishLaunchingWithOptions
使用@Hurden的想法application:didFinishLaunchingWithOptions
,检查applicationState
以查看应用程序是否实际在后台启动。 这使我的应用程序在手机解锁后获取kReachabilityChangedNotification
通知(使用存储的密码启用WiFi连接)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.