嗨我想捕获每当用户在我的应用程序中获得网络连接时,我已经添加了苹果Reachability类,下面是我在appDelegate类中使用的片段didFinishLaunchingWithOptions方法,
Reachability* reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
我的reachabilityChanged选择器方法如下
- (void)reachabilityChanged:(NSNotification*)notification
{
Reachability* reachability = notification.object;
if(reachability.currentReachabilityStatus == NotReachable)
NSLog(@"Internet off");
else
NSLog(@"Internet on");
}
但是在我关闭飞机模式和手机中的网络连接时,我没有收到任何通知。
我错过了什么吗?
答案 0 :(得分:13)
我在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];
// }
}
答案 1 :(得分:6)
也许你应该在startnotifier之前添加观察者
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNetworkChange:) name: kReachabilityChangedNotification object: nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
答案 2 :(得分:0)
只要连接状态发生变化,您就可以使用此包装来获取基于块的回调。
GitHub:UHBConnectivityManager
如果您正在使用cocoapods。
pod 'UHBConnectivityManager'
答案 3 :(得分:0)
最简单的方法:
reach = [Reachability reachabilityWithHostName:@"www.google.com"];
reach.reachableBlock = ^(Reachability *reach){
NSLog(@"Reachable");
};
reach.unreachableBlock = ^(Reachability *reach){
NSLog(@"Unreachable");
};
[reach startNotifier];
每次网络发生变化时,都会调用相应的块。
答案 4 :(得分:0)
将可达性作为您的属性而不是局部变量。它会起作用。