【问题标题】:What happens if disk space runs out while using NSURLSessionDownloadTask in background?如果在后台使用 NSURLSessionDownloadTask 时磁盘空间用完会怎样?
【发布时间】:2025-12-08 19:15:02
【问题描述】:

在 iOS 8.1 应用程序中,我使用 NSURLSessionDownloadTask 在后台下载档案,该档案有时会变得很大。

一切正常,但如果手机磁盘空间不足会怎样?会不会下载失败并提示是剩余磁盘空间的问题?有什么好办法提前查吗?

【问题讨论】:

  • 在开始下载之前,获取文件大小并检查设备中的可用空间。这样您就可以在没有足够的可用空间时通知用户。
  • 这是一种检查可用空间的方法:*.com/questions/5712527/…
  • @Mrunal 这并不能完全解决问题。如果有其他应用在后台下载大文件怎么办?
  • @HAS : 不,你不能检查其他应用在做什么,这是苹果的限制。
  • 是的,我知道 :) 这就是为什么我说您提出的解决方案并不能完全解决问题。 ;-)

标签: ios nsurlsession nsurlsessiondownloadtask


【解决方案1】:

您可以像这样为用户设备获取可用磁盘空间:

- (NSNumber *)getAvailableDiskSpace
{
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/var" error:nil];
    return [attributes objectForKey:NSFileSystemFreeSize];
}

您可能需要开始下载以获取正在下载的文件的大小。 NSURLSession 有一个方便的委托方法,可以在任务恢复时为您提供预期的字节:

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    // Check if we have enough disk space to store the file
    NSNumber *availableDiskSpace = [self getAvailableDiskSpace];
    if (availableDiskSpace.longLongValue < expectedTotalBytes)
    {
        // If not, cancel the task
        [downloadTask cancel];

        // Alert the user
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Low Disk Space" message:@"You don't have enough space on your device to download this file. Please clear up some space and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
}

【讨论】:

    最近更新 更多