How do I repeat a Reachability test until it works

点点圈 提交于 2019-11-30 16:14:02

问题


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.



来源:https://stackoverflow.com/questions/15854409/how-do-i-repeat-a-reachability-test-until-it-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!