嘿伙计们,我在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;
}
答案 0 :(得分: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;
另请参阅方法说明here。