Suppose I have an NSURL that points to my NSDocumentationDirectory but the NSURL has an unknown number of subdirectories in it. When writing to the URL, will have I have to check for existence of the directories along the path and create them if they don't exist, or can I just write to the NSURL? If the former, how do I do it?
Here's what I've tried so far, and it's not working. I assume it's because the subdirectories along the path don't exist.
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]);
}
I am not interested in caching APIs I can tap into. The purpose of this question is to understand how to properly use NSFileManager.
Edit: I'm thinking maybe I need to use createDirectoryAtURL:withIntermediateDirectories:attributes:error: on the path excluding the last component.