目前我正在使用苹果的reachability.m/.h 的类并且它可以工作,除了它会通知我任何更改,因为我只想在网络无法访问时通知用户。目前,如果我有互联网连接,然后松开网络,它会告诉我。但是,当您重新连接到网络时,它也会告诉我,这是我不想要的。我希望它只在网络丢失/无网络时告诉我。
我相信这与电话有关:
- (void)viewWillAppear:(BOOL)animated
{
// check for internet connection
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [[Reachability
reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [[Reachability reachabilityWithHostName:
@"www.google.ca"] retain];
[hostReachable startNotifier];
// now patiently wait for the notification
}
打电话时-[NSNotificationCenter addObserver:selector:name:object:]
,这个名字除了字面上的名字之外还有其他功能吗?这是我第一次使用 NSNotificationCenter,所以我对这件事不太熟悉。
EDIT:
这是我的 checkNetworkStatus 函数:(问题是我收到“NotReachable”,因为网络连接正在恢复并且 NSAlert 多次关闭)
- (void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Network Failed" message:@"Please check your connection and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
[alert show];
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
break;
}
}
}
当状态发生更改时,可达性将发送通知,但您如何处理该通知完全取决于您。如果您不想告诉用户网络已恢复,则不必这样做。
NSNotificationCenter 方法中的“name”参数指示您要订阅的通知。当对象发布通知时,它会使用特定的名称。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)