How do I repeat a Reachability test until it works

2019-02-11 02:44发布

问题:

I have an initial tableviewcontroller which is executing a reachability check. This is working without a problem within the viewDidLoad, however I would like to know the correct way to Retry the connection until it passes. The pertinent code in my implementation file is below, I have tried inserting [self ViewDidLoad] if the connection is down but this just sets the app into a loop (returning the connection failure NSLog message) and not showing the 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];
    }
}

回答1:

How should you use Reachability?

  • Always try your connection first.
  • If the request fails, Reachability will tell you why.
  • If the network comes up, Reachability will notify you. Retry the connection then.

In order to receive notifications, register for the notification, and start the reachability class from Apple:

@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

To answer the notification:

- (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
}

If you rather use blocks instead, use KSReachability.