假设我有一个指向我的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:在不包括最后一个组件的路径上。
答案 0 :(得分:0)
我使用createDirectoryAtURL开始工作:...如下:
for (NSString *pathComponent in passedPathComponents) {
if ([pathComponent isEqualToString:lastComponent]) {
//Now we're looking at the file name. Ensure the directory exists. What we have so far is the directory.
if ([fileManager createDirectoryAtURL:cachedURL withIntermediateDirectories:YES attributes:nil error:NULL]) {
//NSLog(@"Directory was created or already exists");
} else {
NSLog(@"Error creating directory %@",[cachedURL description]);
};
}
cachedURL = [cachedURL URLByAppendingPathComponent:pathComponent];
}