Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 255
Erik Avatar asked Jan 07 '15 08:01

Erik


1 Answers

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];
    }
}
like image 140
lehn0058 Avatar answered Nov 04 '22 12:11

lehn0058