如果在后台使用NSURLSessionDownloadTask时磁盘空间不足会发生什么?

时间:2015-01-07 08:56:46

标签: ios nsurlsession nsurlsessiondownloadtask

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

一切正常,但如果手机磁盘空间不足,会发生什么?下载是否会失败,并表明存在剩余磁盘空间的问题?有没有提前检查的好方法?

1 个答案:

答案 0 :(得分: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];
    }
}