Home > Software design >  NSFileManager createDirectoryAtPath method returns true but no directory was created
NSFileManager createDirectoryAtPath method returns true but no directory was created

Time:11-05

In my app, I want to create a directory and put some txt files in it. Here is my code to create the directory

-(BOOL)createFolderInDocuments:(NSString *)folderName
{
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:folderName];
    
    BOOL success = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        success = [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    
    if(error){
        UIAlertController * alert = [UIAlertController
                                     alertControllerWithTitle:@"Error"
                                     message:[NSString stringWithFormat:@"Create folder: %@", error]
                                     preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* okButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
        [alert addAction:okButton];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    if (success) {
        NSLog(@"Created folder with name %@", folderName);
    }
    return success;
}

After I ran the method, I got this message in console

2021-11-01 15:16:23.786293 0800 my-app[887:167944] Created folder with name 2021-11-01T15-16-23

which means method createDirectoryAtPath returned true.

From my experience by using this repo enter image description here

But I got nothing here. Actually, I couldn't find the directory anywhere on my iPhone. So I guess it was not created at all.

Could anyone tell me how to create the directory correctly? Thanks!

CodePudding user response:

Ok I figured it out. The directory was indeed created, it was just not showing in Finder when the iPhone connected to Mac.

In order to make it show in Finder, add this entitlement in the xcode project info.plist enter image description here

  • Related