0

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

4

1 に答える 1

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];
  }
于 2013-03-28T20:06:48.083 に答える