如何重复可达性测试,直到它的工作原理(How do I repeat a Reachability

2019-08-20 01:37发布

我有正在执行可达性检查的初始tableviewcontroller。 这是工作无内的问题viewDidLoad但是我想知道,直到它传递给重试连接的正确方法。 我在执行文件中的相关代码如下,我试图插入[self ViewDidLoad]如果连接下来,但它仅设置应用到一个循环(返回连接失败NSLog消息),而不是显示UIAlertView

- (void)viewDidLoad
{
    [super viewDidLoad];

    if(![self connected])
    {
        // not connected
        NSLog(@"The internet is down");
        UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection      Error" message:@"There is no Internet Connection" delegate:self cancelButtonTitle:@"Retry" otherButtonTitles:nil, nil];
        [connectionError show];
        [self viewDidLoad];
    } else
    {
        NSLog(@"Internet connection established");
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
        [btn addTarget:self action:@selector(infoButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]    initWithCustomView:btn];
        [self start];
    }
}

Answer 1:

你应该如何使用可达性 ?

  • 总是先尝试连接。
  • 如果请求失败,将可达性告诉你为什么。
  • 如果网络出现时,可达性会通知您。 重试连接即可。

为了从苹果公司收到通知,注册通知,并启动可达类:

@implementation AppDelegate {
    Reachability *_reachability;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NSNotificationCenter defaultCenter]
     addObserver: self
     selector: @selector(reachabilityChanged:)
     name: kReachabilityChangedNotification
     object: nil];

    _reachability = [Reachability reachabilityWithHostName: @"www.apple.com"];
    [_reachability startNotifier];

    // ...
}

@end

要回答通知:

- (void) reachabilityChanged: (NSNotification *)notification {
    Reachability *reach = [notification object];
    if( [reach isKindOfClass: [Reachability class]]) {
    }
    NetworkStatus status = [reach currentReachabilityStatus]; 
    NSLog(@"change to %d", status); // 0=no network, 1=wifi, 2=wan
}

如果你喜欢使用块,而应使用KSReachability 。



文章来源: How do I repeat a Reachability test until it works