21

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

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

4

1 回答 1

9

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

- (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];
    }
}
于 2015-06-11T14:41:17.610 回答