【问题标题】:Constantly Listen for Internet Reachability?不断聆听互联网可达性?
【发布时间】:2013-09-27 12:47:40
【问题描述】:

我了解如何在我的应用中测试互联网可访问性,但我需要做的是在整个应用范围内不断监听可访问性。因此,如果应用程序中任何一点的连接状态发生变化,我都可以做出反应。

我将如何实现这样的目标?

【问题讨论】:

标签: ios objective-c networking reachability


【解决方案1】:

您需要为可达性更改通知添加观察者:

首先在你的类中导入:#import "Reachability.h"

然后添加观察者:

   [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];


-(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;
    NSLog(@"reachabilityChanged");

    Reachability * reach = [note object];

    if([reach isReachable])
    {
        //notificationLabel.text = @"Notification Says Reachable"
        status = YES;
        NSLog(@"NetWork is Available");
    }
    else
    {
        status = NO;
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"You are not connected to the internet" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    return status;
}

【讨论】:

  • 这个答案中隐含的当然是调用startNotifier
  • 另外不要忘记在不需要的时候移除观察者(例如在 viewWillDisappear 中)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多