Reputation: 11686
I have code which creates a folder under the NSHomeDirectory but it always fails and I cannot see why. It should work but it keeps saying the operation is not permitted. Any ideas?
NSURL *homeURL = [NSURL fileURLWithPath:NSHomeDirectory() isDirectory:YES];
NSURL *previewsURL = [homeURL URLByAppendingPathComponent:@"Previews"];
DebugLog(@"homeURL: %@", homeURL);
DebugLog(@"previewsURL: %@", previewsURL);
BOOL isDirectory = TRUE;
if (![[NSFileManager defaultManager] fileExistsAtPath:previewsURL.path isDirectory:&isDirectory]) {
DebugLog(@"isDirectory: %@", isDirectory ? @"YES" : @"NO");
NSAssert(isDirectory, @"Must be a directory");
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:previewsURL.path withIntermediateDirectories:TRUE attributes:nil error:&error]) {
DebugLog(@"Error: %@", error); // WHY?!
}
else {
BOOL isDirectory = TRUE;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:previewsURL.path isDirectory:&isDirectory];
NSAssert(exists, @"Directory must exist");
}
}
Upvotes: 1
Views: 3090
Reputation: 3513
First of all, as pointed out by other answers, you have no permissions to access home directory.
Then, I see you want to save some kind of previews: are they user-generated images, that needs to be saved, or are they just some kind of cached data that is written just to speed-up some kind of process (downloaded images, cached previews of larger versions of images..)?
If this is the case, you shouldn't use the document dir, as it should be used to save user-generated content only, content that your app cannot recreate by itself. The right directory for this kind of purposes is the cache one. If you don't follow this agreement, your App could be rejected by AppStore reviewal process.
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL *cacheURL = [NSURL fileURLWithPath:cacheDirectory isDirectory:YES];
NSURL *previewsURL = [cacheURL URLByAppendingPathComponent:@"Previews"];
Upvotes: 2
Reputation: 9040
You have no permission to access NSHomeDirectory(),
Instead, create them in the documents directory
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSURL *homeURL = [NSURL fileURLWithPath:documentDirectory isDirectory:YES];
NSURL *previewsURL = [homeURL URLByAppendingPathComponent:@"Previews"];
Upvotes: 5
Reputation:
Simple: because you can't/aren't permitted to write to that directory (because it's outside the app sandbox).
Upvotes: 0