ios - 如何从 iOS Reachability Class 获取网络连接通知的变化?

标签 ios objective-c reachability

您好,每当用户在我的应用程序中获得网络连接时,我都想捕获为此我添加了 apples 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");
}

但在这里,当我关闭飞行模式和在我的手机中获得网络连接时,我没有收到任何类型的通知。

我错过了什么吗?

最佳答案

我在 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 - 如何从 iOS Reachability Class 获取网络连接通知的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17804830/

相关文章:

iphone - 在 json 解析过程中出现错误

Objective-C 根据偶数/奇数索引将数组拆分为两个单独的数组

algorithm - 使用元胞自动机对图中的顶点进行可达性分析

iphone - 使用 NSDateFormatter 获取错误时间

ios - UICOllectionview,滚动到标题中包含 NSString 的第一个单元格

iphone - 我应该把我的图像放在我的 iPhone 项目中的什么地方?

nsoperation - 即使操作队列被挂起,AFHTTPRequestOperation 仍在运行

ios - 为什么贝塞尔曲线路径中的 hotTest/tap 检测会在以下情况下产生不准确的结果?

ios - 如何调暗 UITableViewCell

iOS 可达性 : Problem with host Method