我用这个问题来检查互联网连接(WiFi \ 3G)是否处于活动状态。
它工作得很好,但有一个小问题。
当我关闭互联网时,该应用程序会发出互联网已关闭的警报;但是当我再次打开它时,直到连接肯定启动,它说主机已关闭而实际上已启动,事实上,过了一会儿,它记录了它已启动。
我想知道我该怎么做才能让该消息仅在服务器实际关闭时才出现,而不是在重新连接到互联网时出现!
这是我的代码
-(void) checkNetworkStatus:(NSNotification *)notice
{
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
if (internetStatus == NotReachable){
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Reloading Failed" message: @Seems like you're offline! \n Some features, such as updating contents and downloading screenshots won't be available while you're offline.\nNavigate to Settings > Wi-Fi to connect to the Internet and enjoy those features!") delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
[alert show];
[alert release];
NSLog(@"offline");
}
else if (internetStatus == ReachableViaWiFi || internetStatus == ReachableViaWWAN){
NSLog(@"online");
if (hostStatus == NotReachable)
{ NSLog(@"Server offline");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Reloading Failed" message:@"Seems like there's a communication problem with the remote network. \n Please try again in a while!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
[alert show];
[alert release];
}
else if (hostStatus == ReachableViaWWAN || hostStatus == ReachableViaWiFi){
NSLog(@"server online");
//download data from remote server
}
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
hostReachable = [[Reachability reachabilityWithHostName: @"www.mywebsite.com"] retain];
[hostReachable startNotifier];
有任何想法吗?