简体   繁体   中英

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?

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);

Adding additional information to @shpasta's answer here. Suppose you have additional folders inside your Cache directory and you wanna get some files inside those folders. This is how you can get access to files inside those folders.

 NSArray *subFolders = [[NSFileManager defaultManager]subpathsAtPath:yourCacheDirectory];
 NSString* additionalParams;

for(NSString* sub in subFolders){
            if([sub containsString:@".log"]){
                 //Assuming you have .log file inside the folder.
                additionalParams = sub;
            }
        }

 NSString* fullFileURL = [NSString stringWithFormat:@"%@/%@",cacheDirectory,additionalParams];

Hope this helps anybody who is trying to get access to files inside folders which exits inside cache directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM