NSURLSessionTask 在 WiFi 关闭时从不回调

NSURLSessionTask Never Calls Back When WiFi Off

当我关闭 WiFi 连接并在 iPhone 6s 10.2 模拟器上 运行 以下代码时,回调永远不会执行。我预计回调会很快触发,并出现 "No Internet connection".

之类的错误
NSLog(@"request-start");
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:0];
task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSLog(@"request-end");
}];
[task resume];

我的问题

我正在应用首次加载时获取数据。如果 wifi 关闭,我需要显示错误。如果我设置超时,它会被遵守——但它需要超过 10 秒,我不想让他们等待。我也试过通过可达性来检测网络状态,但是当应用程序首次加载时,网络状态通常是 unknown

timeoutIntervalForResource

This property determines the resource timeout interval for all tasks within sessions based on this configuration. The resource timeout interval controls how long (in seconds) to wait for an entire resource to transfer before giving up. The resource timer starts when the request is initiated and counts until either the request completes or this timeout interval is reached, whichever comes first.

The default value is 7 days.

timeoutIntervalForRequest

Important

Any upload or download tasks created by a background session are automatically retried if the original request fails due to a timeout. To configure how long an upload or download task should be allowed to be retried or transferred, use the timeoutIntervalForResource property.

The default value is 60.

因此,如果没有设置超时,您的连接将 运行 持续 7 天。

In general an NSURLSession background session does not fail a task if something goes wrong on the wire. Rather, it continues looking for a good time to run the request and retries at that time. This continues until the resource timeout expires (that is, the value in the timeoutIntervalForResource property in the NSURLSessionConfiguration object you use to create the session). The current default for that value is one week!

Source