嘿伙计们,我在使用 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;
}