Bạn có thể lấy không gian đĩa có sẵn cho một thiết bị sử dụng như thế này:
- (NSNumber *)getAvailableDiskSpace
{
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:@"/var" error:nil];
return [attributes objectForKey:NSFileSystemFreeSize];
}
Bạn có thể sẽ cần phải bắt đầu tải về để có được kích thước của tập tin bạn đang tải về. Có một phương pháp thuận tiện đại biểu cho NSURLSession cung cấp cho bạn các byte dự kiến đúng như nhiệm vụ được khôi phục:
- (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];
}
}
Trước khi bắt đầu tải về, có được kích thước tập tin và kiểm tra không gian trống trong thiết bị. Để bạn có thể thông báo cho người dùng nếu không có đủ dung lượng trống. – Mrunal
Đây là cách để kiểm tra dung lượng trống: http://stackoverflow.com/questions/5712527/how-to-detect-total-available-free-disk-space-on-the-iphone-ipad-device – Mrunal
@Mrunal Điều đó không hoàn toàn giải quyết được vấn đề. Điều gì sẽ xảy ra nếu có một ứng dụng khác tải xuống một tệp lớn trong nền? – HAS