What happens if disk space runs out while using NSURLSessionDownloadTask in background?
Asked Answered
C

1

21

In a iOS 8.1 app I am using NSURLSessionDownloadTask to download an archive in the background which can sometimes get quite large.

Everything works fine, but what will happen if the phone runs out of disk space? Will the download fail and indicate that it was a problem of remaining disk space? Is there any good way to check in advance?

Cerebrum answered 7/1, 2015 at 8:56 Comment(5)
Before starting download, get the file size and check the free space in device. So that you can notify user if there is no enough free space.Cornelia
Here is a way to check free space: #5713027Cornelia
@Cornelia That doesn't completely solve the problem. What if there's another app downloading a large file in the background?Cumbersome
@Cumbersome : No, you cannot check what other apps are doing, that's the restriction by Apple.Cornelia
Yeah I know :) That's why I said that your proposed solution doesn't completely solve the problem. ;-)Cumbersome
S
9

You can get the available disk space for a users device like this:

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

You will likely need to start the download to get the size of the file you are downloading. There is a convenient delegate method for NSURLSession that gives you the expected bytes right as the task is resuming:

- (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];
    }
}
Slipon answered 11/6, 2015 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.