2

我有一个初始的 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];
    }
}
4

1 回答 1

3

你应该如何使用可达性

  • 始终先尝试您的连接。
  • 如果请求失败,Reachability 会告诉你原因。
  • 如果网络出现,可达性会通知您。然后重试连接。

为了接收通知,注册通知,并从 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

回复通知:

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

于 2013-04-06T18:59:19.400 回答