假设我有一个指向我的 NSDocumentationDirectory 的 NSURL,但 NSURL 中有未知数量的子目录。写入 URL 时,我是否必须检查路径上的目录是否存在,如果它们不存在则创建它们,或者我可以只写入 NSURL 吗?如果是前者,我该怎么做?
这是我迄今为止尝试过的,但它不起作用。我认为这是因为路径上的子目录不存在。
NSData *imageData;
if (imageURL) {
//imageURL points to an image on the internet.
NSLog(@"Path components\n%@",[imageURL pathComponents]);
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask];
//Sample of urls[0]: file://localhost/var/mobile/Applications/blahblah/Library/Documentation/
NSURL *cachedURL = urls[0]; //iOS, so this will be the only entry.
//Manually add a cache directory name.
cachedURL = [cachedURL URLByAppendingPathComponent:@"cache"];
NSArray *passedPathComponents = [imageURL pathComponents];
for (NSString *pathComponent in passedPathComponents) {
cachedURL = [cachedURL URLByAppendingPathComponent:pathComponent];
NSLog(@"Added component %@ making URL:\n%@",pathComponent,cachedURL);
}
// Check if image data is cached.
// If cached, load data from cache.
imageData = [[NSData alloc] initWithContentsOfURL:cachedURL];
if (imageData) {
//Cached image data found
NSLog(@"Found image data from URL %@",cachedURL);
} else {
// Did not find the image in cache. Retrieve it and store it.
// Else (not cached), load data from passed imageURL.
// Update cache with new data.
imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
if (imageData) {
// Write the imageData to cache
[imageData writeToURL:cachedURL atomically:YES]; //This is the line I'm asking about
}
}
NSLog(@"Value of urls is %@",urls[0]);
}
我对可以利用的缓存 API 不感兴趣。这个问题的目的是了解如何正确使用 NSFileManager。
编辑:我在想也许我需要在不包括最后一个组件的路径上使用 createDirectoryAtURL:withIntermediateDirectories:attributes:error: 。