20

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?

Erik
  • 11,034
  • 17
  • 75
  • 120
  • 1
    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. – Mrunal Jan 07 '15 at 09:51
  • 1
    Here is a way to check free space: http://stackoverflow.com/questions/5712527/how-to-detect-total-available-free-disk-space-on-the-iphone-ipad-device – Mrunal Jan 07 '15 at 09:52
  • @Mrunal That doesn't completely solve the problem. What if there's another app downloading a large file in the background? – HAS Jun 12 '15 at 06:30
  • @HAS : No, you cannot check what other apps are doing, that's the restriction by Apple. – Mrunal Jun 12 '15 at 06:59
  • Yeah I know :) That's why I said that your proposed solution doesn't completely solve the problem. ;-) – HAS Jun 12 '15 at 07:02

1 Answers1

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];
    }
}
lehn0058
  • 19,077
  • 14
  • 65
  • 107