如何从iOS Reachability Class获取networking连接通知的更改?
嗨,我想捕获每当用户在我的应用程序中获得networking连接,我已经添加了苹果可达性类和以下是我在我的appDelegate类didFinishLaunchingWithOptions方法中使用的代码段,
Reachability* reachability = [Reachability reachabilityForInternetConnection]; [reachability startNotifier]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
和我的reachabilityChangedselect器的方法如下
- (void)reachabilityChanged:(NSNotification*)notification { Reachability* reachability = notification.object; if(reachability.currentReachabilityStatus == NotReachable) NSLog(@"Internet off"); else NSLog(@"Internet on"); }
但在这里我没有得到任何forms的通知,当我closures我的飞行模式,当我在我的手机networking连接。
我错过了什么?
我在appdelegate中使用一个variables来存储当前的networking状态作为布尔值
@property (nonatomic, assign) BOOL hasInet;
.M
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self setUpRechability]; } -(void)setUpRechability { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil]; reachability = [Reachability reachabilityForInternetConnection]; [reachability startNotifier]; NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; if (remoteHostStatus == NotReachable) {NSLog(@"no"); self.hasInet-=NO; } else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); self.hasInet-=YES; } else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); self.hasInet-=YES; } } - (void) handleNetworkChange:(NSNotification *)notice { NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; if (remoteHostStatus == NotReachable) {NSLog(@"no"); self.hasInet-=NO; } else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); self.hasInet-=YES; } else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); self.hasInet-=YES; } // if (self.hasInet) { // UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Net avail" message:@"" delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil]; // [alert show]; // } }
也许你应该在startnotifier之前添加观察者
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNetworkChange:) name: kReachabilityChangedNotification object: nil]; reachability = [Reachability reachabilityForInternetConnection]; [reachability startNotifier];
只要连接状态发生变化,您就可以使用这个可达性包装来获取基于块的callback。
GitHub: UHBConnectivityManager
如果你正在使用椰子树。
pod 'UHBConnectivityManager'
最简单的方法:
reach = [Reachability reachabilityWithHostName:@"www.google.com"]; reach.reachableBlock = ^(Reachability *reach){ NSLog(@"Reachable"); }; reach.unreachableBlock = ^(Reachability *reach){ NSLog(@"Unreachable"); }; [reach startNotifier];
每当networking发生变化时,都会调用相应的块。
使可达性成为您的财产,而不是本地variables。 这将工作。