最近使用NSURLSession做下載時,配置了NSURLSessionConfiguration為backgroundSessionConfiguration,
在下載時發現拔下iPhone拔下電源后,點擊下載無任何進度,連接電源后即可正常下載,最終發現是NSURLSessionConfiguration的discretionary設置為了YES導致;
此屬性在官方API文檔的定義為:
/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(10_10, 7_0);
此屬性設置為YES時,系統根據當前性能自動處理后臺任務的優先級,以獲得最佳性能 (僅background session有效),
但是我用的測試機為iPhone7,且電量是滿滿的。
經查閱:allowsCellularAccess 和 discretionary 被用于節省通過蜂窩連接的帶寬。建議在使用后臺傳輸的時候,使用discretionary屬性,而不是allowsCellularAccess屬性,因為它會把WiFi和電源可用性考慮在內。