Search code examples
iosobjective-cnsfilemanager

iOS: Can't get content of Caches directory


Trying to get content of Caches directory:

NSError *error;
NSString *path = [[self.class cachesDirectoryURL] absoluteString];
NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];

path is correct, I can see in Finder that it exists and contains my files.
directoryItems is nil and error is

Error Domain=NSCocoaErrorDomain Code=260 "The folder “Caches” doesn’t exist." UserInfo={NSUnderlyingError=0x7982d2d0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=file:///Users/seelts/Library/Developer/CoreSimulator/Devices/C1411C3D-91FB-4D91-83A4-D0747071AE36/data/Containers/Data/Application/800DE429-F10C-438E-BB04-2948C0B07E7C/Library/Caches/, NSUserStringVariant=(
    Folder
)}

What's wrong with me?


Solution

  • You are using wrong path. To get right cache directory for the app use this:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    

    In cacheDirectory you will receive string path like this (whithout file scheme):

    /Users/username/Library/Developer/CoreSimulator/Devices/D55805E2-50FF-4D8D-8D04-490001AD6071/data/Containers/Data/Application/DE437461-E0F8-4C11-861E-2D1C56CDF6F1/Library/Caches
    


    The whole code:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    
    NSError *error;
    NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cacheDirectory error:&error];
    NSLog(@"%@", directoryItems);