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];
}
}