Unable to create directory under NSHomeDirectory

穿精又带淫゛_ 提交于 2019-12-12 02:29:57

问题


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");
    }
}

回答1:


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"];



回答2:


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"];



回答3:


Simple: because you can't/aren't permitted to write to that directory (because it's outside the app sandbox).



来源:https://stackoverflow.com/questions/16325065/unable-to-create-directory-under-nshomedirectory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!