嗨,我想要捕获每当用户在我的应用程序中获取网络连接我已经添加了苹果可达性类和下面是我在我的appDelegate类didFinishLaunchingWithOptions方法中使用的片段,
Reachability* reachability = [Reachability reachabilityForInternetConnection]; [reachability startNotifier]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
而我的可达性更改选择器方法如下
- (void)reachabilityChanged:(NSNotification*)notification { Reachability* reachability = notification.object; if(reachability.currentReachabilityStatus == NotReachable) NSLog(@"Internet off"); else NSLog(@"Internet on"); }
但是当我关闭我的飞行模式,以及当我在手机中获得网络连接时,我没有收到任何通知.
我错过了什么吗?
解决方法
我使用appdelegate中的变量将当前网络状态存储为bool
@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]; // } }