目前,我正在使用苹果可达性/ / .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,所以我不太懂这件事情.
编辑:
这是我的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”参数指示您订阅的通知.当一个对象发布通知时,它以特定的名称进行.