gpt4 book ai didi

ios - 实时检查网络可达性

转载 作者:行者123 更新时间:2023-11-29 10:56:20 25 4
gpt4 key购买 nike

当用户按下按钮时,我需要知道设备在那一刻是否连接到互联网——而不是他是否在 3 秒前连接过。在网络可达性发生变化后,可达性 (tonymillion) 通知程序大约需要很长时间才能更新。

我认为我可以使用以下方法实时检查实际访问:

if (!([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable)) NSLog(@"reachable");
if ([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable) NSLog(@"not reachable");

但结果表明,实际上 currentReachabilityStatus 不检查互联网访问;它只检查延迟约 3 秒更新的相同标志。

现场实际检查网络访问的有效方法是什么?

最佳答案

正如您在上面的评论中所希望的那样,这是一个使用“HEAD”请求的解决方案。

  1. 让你的类(class)符合 NSURLConnectionDelegate .
  2. 实现connection:didReceiveResponse:委托(delegate)方法
  3. 可选地实现 connection:didFailWithError: 委托(delegate)方法

因此您的设置可能如下所示:

你的类(class).m

@interface YourClass () <NSURLConnectionDelegate>
@property (strong, nonatomic) NSURLConnection *headerConnection;
@end

@implementation YourClass

- (void)viewDidLoad {
// You can do this in whatever method you want
NSMutableURLRequest *headerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
headerRequest.HTTPMethod = @"HEAD";
self.headerConnection = [[NSURLConnection alloc] initWithRequest:headerRequest delegate:self];
}

#pragma mark - NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection == self.headerConnection) {
// Handle the case that you have Internet; if you receive a response you are definitely connected to the Internet
}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Note: Check the error using `error.localizedDescription` for getting the reason of failing
NSLog(@"Failed: %@", error.localizedDescription);
}

关于ios - 实时检查网络可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152340/

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