gpt4 book ai didi

ios - 设备进入休眠模式时临时部署中的背景 NSURLSession 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:21 24 4
gpt4 key购买 nike

我必须下载一长串文件,因此所有这些操作可能需要很长时间。我决定使用后台配置实例化的 NSURLSession 来管理这些下载任务。在我的 iPhone 上构建并运行代码后,我尝试测试应用程序拔掉设备并在没有 xCode 的情况下启动应用程序。在那种情况下,我注意到如果连接不是通过 WiFi,下载将不再开始。此外,我注意到,在下载操作期间,如果设备进入休眠模式,几秒钟(10-15 秒)后解锁应用程序将重新启动并停止下载。我不知道这是否重要,但我希望 iOS 8.2 中不存在这些问题(现在我使用的是 iOS 8.3)。

我的 session 配置如下

NSString *sessionIdentifier = @"com.yourappfor.example";
NSURLSessionConfiguration *sessionConfiguration;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier];
} else {
sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier];
}
[sessionConfiguration setAllowsCellularAccess:YES];
[sessionConfiguration setSessionSendsLaunchEvents:YES];
[sessionConfiguration setURLCache:nil];
[sessionConfiguration setDiscretionary:YES];
[sessionConfiguration setTimeoutIntervalForRequest:90.0];
[sessionConfiguration setTimeoutIntervalForResource:43200.0];
[sessionConfiguration setHTTPMaximumConnectionsPerHost:15];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

最佳答案

正如其他地方所讨论的(例如,参见 https://stackoverflow.com/a/25653066/1271826 ),当您使用 discretionary 时,它可能会在开始请求之前考虑 wifi 状态。正如 discretionary 文档所说:

When transferring large amounts of data, you are encouraged to set the value of this property [i.e., discretionary] to YES. Doing so lets the system schedule those transfers at times that are more optimal for the device. For example, the system might delay transferring large files until the device is plugged in and connected to the network via Wi-Fi. The default value of this property is NO.

我已经通过经验证实了这一点:

  • 我关闭了 wifi,启动了一个自主后台 session ,插上了我的设备,并放置了一夜,当我早上起床时,我的请求仍然没有被执行.只有当我打开 wifi 时,他们才会继续(而且似乎很快)。

  • 我在第二天晚上重复了这个练习,这次关闭了 discretionary。这一次,请求得到执行,但不是立即执行。他们在大约 10 分钟后完成(顺便说一句,如果正常执行,他们可能只需要不到一分钟左右的时间,因此仅蜂窝网络的后台连接速度要慢得多)。

最重要的是,discretionary 将在执行请求时考虑 wifi 状态,但关闭 discretionary 后,请求将在没有 wifi 的后台 session 中执行,尽管速度不是很快。


但应注意,这仅适用于您在应用程序处于前台时启动的任务。正如 discretionary 文档继续说的那样:

The session object applies the value of this [i.e., discretionary] property only to transfers that your app starts while it is in the foreground. For transfers started while your app is in the background, the system always starts transfers at its discretion—in other words, the system assumes this property is YES and ignores any value you specified.

关于ios - 设备进入休眠模式时临时部署中的背景 NSURLSession 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29616196/

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