gpt4 book ai didi

xcode - 我如何重复可达性测试直到它起作用

转载 作者:行者123 更新时间:2023-12-04 05:03:17 28 4
gpt4 key购买 nike

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

最佳答案

您应该如何使用 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
    }

    如果您更愿意使用块,请使用 KSReachability .

    关于xcode - 我如何重复可达性测试直到它起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854409/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com