私の 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: を使用する必要があるのではないかと考えています。