0

嘿伙计们,我在使用 Apple 的可达性代码时遇到了一些问题。我发现,即使设备正确连接到互联网,最初可达性代码也会发出 1 个错误通知(Networkstatus = NotReachable),然后是几个正确通知(Networkstatus = ReachableViaWiFi)。因此,当我收到“NotReachable”通知时显示 UIAlertView 时,即使设备已连接到互联网,应用程序仍会输出 uialertview 通知用户设备未连接。

有没有办法避免这种不便?

任何帮助将非常感激。

这是我的代码:

在我的 .h 文件中:

@property (nonatomic, retain) Reachability *hostReach;

在我的 .m 文件中:

- (void)viewDidLoad
{
    self.hostReach = [Reachability reachabilityWithHostname:@"www.google.com"];

    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    [_hostReach startNotifier];


    NetworkStatus netStatus = [self.hostReach currentReachabilityStatus];


    if(netStatus == NotReachable && _alertShowing==NO){

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                    message:@"No internet connection found"

                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles: nil];

        _alertShowing = YES;

        [alert show];

    }

    ...

}


-(void)reachabilityChanged:(NSNotification *)note {

    Reachability* curReach = [note object];

NSParameterAssert([curReach isKindOfClass: [Reachability class]]);    

    NetworkStatus netStatus = [curReach currentReachabilityStatus];


    if(netStatus == NotReachable && _alertShowing==NO){

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                    message:@"No internet connection found"

                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles: nil];

        _alertShowing = YES;

        [alert show];

    }


-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    _alertShowing = NO;

}
4

1 回答 1

1

你为什么用reachabilityWithHostname:@"www.google.com"?此方法检查特定主机的可达性(在您的情况下google.com)。如果 Google 可用或不可用,您会收到通知。Google 可能会阻止您,您将收到NotReachable状态。

尝试使用:

//reachabilityForInternetConnection- checks whether the default route is available.  
//  Should be used by applications that do not connect to a particular host
+ (Reachability*) reachabilityForInternetConnection;

还可以在这里查看方法描述。

于 2012-11-12T21:22:55.370 回答