2

我用这个问题来检查互联网连接(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];

有任何想法吗?

4

1 回答 1

3

Reachability仅用于检查网络是否可访问,不会告诉您服务器是否已关闭。您将需要使用一个或其他第三方库的组合ReachabilityNSURLConnection检查 HTTP 状态 200 和其他有效状态。您将使用Reachability显示设备没有连接的消息,一旦连接,您将使用 Web 请求通知用户服务器是否在线。在为您的设备重新打开互联网后,您对连接延迟无能为力,因为打开收音机并连接到手机网络或 wifi 需要时间。

于 2012-08-30T19:30:22.340 回答