我已经实现了可达性Api 2.2。当网络从关闭状态变为开启状态时,它不会触发。
另外,我可以在应用程序委托中实现它吗?如果是这样,我应该在哪里删除观察者?
这是我的代码(不调用解雇模型viewController)
- (void)viewDidLoad
{
// 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.com"] retain];
[hostReachable startNotifier];
}
- (void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus hoststatus=[hostReachable currentReachabilityStatus];
NetworkStatus internetStatus=[internetReachable currentReachabilityStatus];
for (NSString *msg in messageArray) {
[stringg appendString:[NSString stringWithFormat:@"%@",msg]];
}
if (hoststatus==NotReachable||internetStatus==NotReachable) {
[self.navigationController presentModalViewController:inter animated:YES];
}
else{
[self dismissModalViewControllerAnimated:YES];
}
[inter release];
}
- (void)viewDidUnload
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidUnload];
}
最佳答案
您在哪里注册通知?
您需要这样的东西:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChange:)
name:kReachabilityChangedNotification
object:nil];
我使用作为参数传递的可达性对象,如下所示:
- (void) reachabilityChange: (NSNotification*) notification
{
Reachability* curReach = [notification object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
BOOL isServerCurrentlyReachable = (NotReachable != [curReach currentReachabilityStatus]);
BOOL wasServerPreviouslyReachable = self.isServerReachable;
self.isServerReachable = isServerCurrentlyReachable;
if (NO == wasServerPreviouslyReachable && YES == isServerCurrentlyReachable)
{
// Moving from non reachable to reachable state
}
else if (YES == wasServerPreviouslyReachable && NO == isServerCurrentlyReachable)
{
// Moving from a reachable to a non reachable state
}
}
您似乎没有使用它。
同样,通知也可以多次以相同的状态被调用,因此您需要确保将其考虑在内,如代码段所示。
如果您在应用程序委托中使用它,则停止/删除applicationDidResignActive中的内容似乎是合适的地方。
关于objective-c - 可达性类(class)在iOS中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10790081/