Jerem
Jerem

Reputation: 23

iOS 9 / 10 -> how to check free / available space

I try to check free available space on iOS 9 and above in objective C. For iOS 11 it is easy : NSURLVolumeAvailableCapacityForImportantUsageKey It works fine ! I get 26GB.

But for iOS 9 / 10 I don't know ho to do this. I try this function :

    //Get free space on the mobile
-(uint64_t)getFreeDiskspace {
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }

    return totalFreeSpace;
}

But the result is wrong, I get 18GB for the same device.

Have you any idea ?

thank you :)

Upvotes: 1

Views: 211

Answers (1)

shubham
shubham

Reputation: 631

For iOS >= 6.0 you can use the new NSByteCountFormatter. This code gets the number of free bytes remaining as a formatted string.

NSError *error = nil;
NSArray * const paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES);
NSDictionary * const pathAttributes = [[NSFileManager defaultManager] 
attributesOfFileSystemForPath:[paths firstObject] error:&error];
NSAssert(pathAttributes, @"");
NSNumber * const fileSystemSizeInBytes = [pathAttributes objectForKey: 
NSFileSystemFreeSize];
const long long numberOfBytesRemaining = [fileSystemSizeInBytes longLongValue];
NSByteCountFormatter *byteCountFormatter = [[NSByteCountFormatter alloc] init];
NSString *formattedNmberOfBytesRemaining = [byteCountFormatter 
stringFromByteCount:numberOfBytesRemaining];

Upvotes: 1

Related Questions