当我的应用程序启动时,我会检查可访问性,因为我需要立即连接互联网。不过,我的问题是,似乎没有立即确认NetworkStatus
,这意味着在设置可达性之后,我检查是否有连接,然后返回没有连接,无论我是否真的在 WiFi 上/3G,或已关闭无线电。
我可以确认我实际上正在获得 Internet 连接,因为在 applicationDidFinishLaunching 之后立即有一个通知,然后记录“ReachableViaWiFi”..
我究竟做错了什么?为什么它没有立即确认有效的 Internet 连接?
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
if (netStatus == NotReachable) {
ErrorViewController *errorViewController = [[ErrorViewController alloc] initWithNibName:@"ErrorView" bundle:[NSBundle mainBundle]];
[tabBarController.view removeFromSuperview];
[window addSubview:[errorViewController view]];
return;
}
}
-(void)setupReachability {
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name:kReachabilityChangedNotification object: nil];
hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
[hostReach startNotifier];
}
-(void)reachabilityChanged:(NSNotification *)notification {
Reachability* curReach = [notification object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus netStatus = [curReach currentReachabilityStatus];
BOOL connectionRequired = [curReach connectionRequired];
switch (netStatus)
{
case NotReachable:
{
[[NSUserDefaults standardUserDefaults] setInteger:kNOTREACHABLE forKey:kREACHABILITYSTATUS];
NSLog(@"NotReachable");
connectionRequired = NO;
break;
}
case ReachableViaWWAN:
{
[[NSUserDefaults standardUserDefaults] setInteger:kREACHABLEVIAWWAN forKey:kREACHABILITYSTATUS];
NSLog(@"ReachableViaWWAN");
break;
}
case ReachableViaWiFi:
{
[[NSUserDefaults standardUserDefaults] setInteger:kNOTREACHABLE forKey:kREACHABILITYSTATUS];
NSLog(@"ReachableViaWiFi");
break;
}
}
}