gpt4 book ai didi

ios - 检查是否可以上网

转载 作者:行者123 更新时间:2023-11-28 18:14:46 25 4
gpt4 key购买 nike

在我的应用程序中,我只想在可以访问互联网时进行网络调用。

注意:我连接到一个没有互联网的 WiFi 点

我想测试 Internet 是否可用。我尝试按照 here 所述使用可达性我还尝试了一个更简单的解决方案,如 here 所述

问题在于,Reachability 会返回 Internet 可以访问的信息,而实际上是无法访问的。另一个解决方案需要太多时间才能做出回应。我尝试为请求和 session 设置超时间隔,但它被忽略了。

如果我连接到没有互联网的 wifi,如何测试互联网可达性?

这里是我使用的一些代码:

- (void) postAsyncTaskWithUrl:(NSString*)urlString
andType:(NSString*)requestType
andToken:(NSString*)token
andPropertiesObject:(id)propObject
urlEncoded:(BOOL)isUrlEncoded
withSuccess:(nullable void(^)(id _Nullable))success
andFailure:(nullable void(^)(id _Nullable))failure
{

internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

__weak typeof(self) weakSelf = self;
// Internet is reachable
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlSt];
[request setTimeoutInterval:20]; //Ignored ... WHY?

NSURLSessionConfiguration *sessionConfigurations = [NSURLSessionConfiguration defaultSessionConfiguration];
[sessionConfigurations setTimeoutIntervalForRequest:20]; //Ignored ... WHY?
[sessionConfigurations setTimeoutIntervalForResource:20]; //Ignored ... WHY?
// NSURLSession *session = [NSURLSession sharedSession];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfigurations];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


}

}

}

最佳答案

尽管这是过去历史上做过的事情,但我认为不值得尝试检查网络是否可达,因为这不是可靠的事情,也不是发出请求之前应该做的事情现在几乎在所有情况下。

根据 Apple's official documentation :

Always attempt to make a connection. Do not attempt to guess whether network service is available, and do not cache that determination

类似blog post from Jared Sinclair on this topic ,使用 SCNetworkReachability(这是 Reachability 库在底层使用的):

SCNetworkReachability should only be used to influence what you do about a network request that has already failed, not an initial request that has yet to be attempted. Use a negative status to determine whether or not you attempt an automatic retry, or to tweak the user-facing language of an alert. Use a positive status to consider retrying an earlier failed request. Never prevent a user-initiated request from being attempted just because SCNetworkReachability thinks there’s not a reachable network

借自a recent Reddit thread :

Reachability is one or "these topics" in iOS world. What does it mean that the Internet is reachable? Even if you check network interfaces, you may not be able to reach apple.com or google.com. Even if you reach Google, you may not be able to reach your on-prem server or cloud. If you check whether you can reach your server of interest, why not to send a request straight away?

关于ios - 检查是否可以上网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649640/

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