如何从iOS可达性类更改网络连接通知?

前端之家收集整理的这篇文章主要介绍了如何从iOS可达性类更改网络连接通知?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我想要捕获每当用户在我的应用程序中获取网络连接我已经添加了苹果可达性类和下面是我在我的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];
//    }
}

猜你在找的iOS相关文章