IOS: cannot get contents of Caches directory

Trying to get the contents of the Caches directory:

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

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

 Error Domain=NSCocoaErrorDomain Code=260 "The folder "Caches" doesnt 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 is wrong with me?

+7
source share
2 answers

You are using the wrong path. To get the correct cache directory for the application, use this:

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

In cacheDirectory you will get a path like this (without a file scheme):

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


All code:

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

Adding more info to @shpasta's answer here. Suppose you have additional folders inside your Cache directory, and you want to get some files inside these folders. Here is how you can access the files inside these 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 anyone trying to access files inside folders that go inside the cache directory.

0
source

Source: https://habr.com/ru/post/1243163/


All Articles