试图获取Caches目录的内容:
NSError *error; Nsstring *path = [[self.class cachesDirectoryURL] absoluteString]; NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
路径是正确的,我可以在Finder中看到它存在并包含我的文件.
directoryItems是nil,错误是
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 )}
我怎么了?
解决方法
你使用错误的路径.要为应用程序获取正确的缓存目录,请使用此:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES); Nsstring *cacheDirectory = [paths objectAtIndex:0];
在cacheDirectory中,您将收到这样的字符串路径(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
整个代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,YES); Nsstring *cacheDirectory = [paths objectAtIndex:0]; NSError *error; NSArray *directoryItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cacheDirectory error:&error]; NSLog(@"%@",directoryItems);