0
假設我有一個NSURL指向我的NSDocumentationDirectory,但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:在路徑中排除最後一個組件。