简体   繁体   中英

NSFileManager doesn't create folder

- (NSURL *) applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

....

NSURL *folder = [[[Database sharedInstance] applicationDocumentsDirectory] URLByAppendingPathComponent:@"temp"];
BOOL isFolder;
NSLog(@"URL: %@", folder);
if ([[NSFileManager defaultManager] fileExistsAtPath:folder.absoluteString isDirectory:&isFolder] == NO)
{
    NSLog(@"IsFolder: %d", isFolder);
    [[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
    if (error)
        NSLog(@"Error: %@", error.localizedDescription);
}

I run this part of code twice.

I expect that the folder will be created, but every time I receive a log: "IsFolder: 7".

Why the folder wasn't created after the first run?

The problem was in folder.absoluteString .

It should be folder.path instead.

Please, replace folder.absoluteString to folder, your problem will be solved.

Follow step by step:

1) Get documents folder

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0]; 

2) Get documents folder and folder name

NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];

3) Check alerdy exists or not

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){

    NSError* error;
    if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])

        else
        {
            NSLog(@"[%@] ERROR: attempting to write create MyFolder directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM