How to detect total available/free disk space on the iPhone/iPad device?

后端 未结 18 2064
别跟我提以往
别跟我提以往 2020-11-22 11:14

I\'m looking for a better way to detect available/free disk space on the iPhone/iPad device programmatically.
Currently I\'m using the NSFileManager to detect the disk s

18条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 11:36

    UPDATE: Since a lot of time has passed after this answer and new methods/APIs have been added, please check the updated answers below for Swift etc; Since I've not used them myself, I can't vouch for them.

    Original answer: I found the following solution working for me:

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

    It returns me exactly the size that iTunes displays when device is connected to machine.

提交回复
热议问题