Search code examples
iosobjective-ciphonediskspace

Is there a way to detect used disk space for the application?


I need to check if my application uses more than 300mb disk space. How can I do this?


Solution

  • Using this answer to find the size of a folder

    - (unsigned long long int)folderSize:(NSString *)folderPath {
        NSArray *filesArray = 
         [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folderPath 
                                                             error:nil];
        NSEnumerator *filesEnumerator = [filesArray objectEnumerator];
        NSString *fileName;
        unsigned long long int fileSize = 0;
    
        while (fileName = [filesEnumerator nextObject]) {
         NSDictionary *fileDictionary = 
          [[NSFileManager defaultManager] 
            attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:fileName] 
                             error:nil];
            fileSize += [fileDictionary fileSize];
        }
    
        return fileSize;
    }
    

    Call this

    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *documentsDirectory = 
     [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                          NSUserDomainMask, 
                                          YES) objectAtIndex:0];
    NSString *cachesDirectory = 
     [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 
                                          NSUserDomainMask, 
                                          YES) objectAtIndex:0];
    
    unsigned long long int bundleSize = [self folderSize:bundlePath];
    unsigned long long int docsSize = [self folderSize:documentsDirectory];
    unsigned long long int cachesSize = [self folderSize:cachesDirectory];
    
    long double totalSize = (bundleSize + docsSize + cachesSize)/1024.0/1024.0; 
    

    This will give you the size of your app's bundle, documents directory, and caches directory in megabytes.