尝试获取Caches目录的内容:
NSError *error;
NSString *path = [[self.class cachesDirectoryURL] absoluteString];
NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
path
是正确的,我可以在Finder中看到它存在且包含我的文件
directoryItems
为nil
,error
为
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
)}
我怎么了?
答案 0 :(得分:13)
您使用的是错误的路径。要为应用程序获取正确的缓存目录,请使用:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
在cacheDirectory
中,您将收到这样的字符串路径(没有file
方案):
/Users/username/Library/Developer/CoreSimulator/Devices/D55805E2-50FF-4D8D-8D04-490001AD6071/data/Containers/Data/Application/DE437461-E0F8-4C11-861E-2D1C56CDF6F1/Library/Caches
整个代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
NSError *error;
NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cacheDirectory error:&error];
NSLog(@"%@", directoryItems);
答案 1 :(得分:0)
在此处向@ shpasta的答案添加其他信息。 假设您在Cache目录中有其他文件夹,并且您想在这些文件夹中获取一些文件。 这是您可以访问这些文件夹中的文件的方法。
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];
希望这可以帮助任何试图访问缓存目录内部文件夹内文件的人。