OGeek|极客世界-中国程序员成长平台

标题: ios - 当设备进入休眠模式时,临时部署中的后台 NSURLSession 问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 06:23
标题: ios - 当设备进入休眠模式时,临时部署中的后台 NSURLSession 问题

我必须下载一长串文件,因此所有这些操作可能需要很长时间。我决定使用后台配置实例化的 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];



Best Answer-推荐答案


正如其他地方所讨论的(例如,参见 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.

我已经凭经验证实了这一点:

底线,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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4