我有一个正在执行可达性检查的初始 TableView Controller 。这在 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];
}
}
最佳答案
你应该如何使用Reachability ?
- 始终先尝试连接。
- 如果请求失败,Reachability 会告诉您原因。
- 如果网络可用,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
}
如果您更愿意使用 block ,请使用 KSReachability .
关于xcode - 如何重复可达性测试直至其正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854409/