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?
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With