Search code examples
iphoneiosnsfilemanager

Creating file in Library directory on iphone


I'm trying to create files in subdirectory inside my app Library dir. First at all I'm getting path to Library like this:

- (NSURL*) getLibraryDirectory
{
    NSFileManager* manager = [NSFileManager defaultManager];
    NSArray* paths = [manager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];

    if ([paths count] > 0)
    {
        return [paths objectAtIndex:0];
    }
    return nil;
}

Then I create subfolder using this code:

- (NSURL*) getDirectory:(NSString*)subdirName
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSURL* libraryDirectory = [self getLibraryDirectory];

    if (libraryDirectory)
    {
        NSURL* subdir = [libraryDirectory URLByAppendingPathComponent:subdirName isDirectory:YES];
        if (![sharedFM fileExistsAtPath:[subdir absoluteString] isDirectory:YES])
        {
            NSError* error;
            if ([sharedFM createDirectoryAtURL:subdir withIntermediateDirectories:YES attributes:nil error:&error])
            {
                return subdir;
            } 
            else 
            {
                NSLog(@"Error occured while trying to create subdirectory \"%@\". Code - %d, desc - %@", subdirName, [error code], [error localizedDescription]);
            }
        }
    }
    return nil;
}

and last thing I'm trying to create some file in this folder like this:

NSString* filePath = [[self getDirectory:DIR_COMMANDS] absoluteString];
if (filePath)
{
    filePath = [filePath stringByAppendingPathComponent:@"test_file.tst"];       

    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager createFileAtPath:filePath contents:[[NSData alloc] initWithBytes:[[@"string" dataUsingEncoding:NSUTF16LittleEndianStringEncoding] bytes] length:12] attributes:nil])
    {
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO");
    }
}

But unfortunately I'm getting "NO" every time and can't understand why.


Solution

  • To get a path from a file URL you have to use path instead of absoluteString.

    NSString *filePath = [[self getDirectory:DIR_COMMANDS] path];
    

    Side note: You should adopt Cocoa's naming style for methods: libraryDirectory instead of getLibraryDirectory, or even better: libraryDirectoryURL. The get prefix is only used if return values are passed by reference.

    Also: Your usage of fileExistsAtPath:isDirectory: is incorrect. The BOOL parameter is passed by reference:

    BOOL isDir;
    if ([sharedFM fileExistsAtPath:[subdir path] isDirectory:&isDir]) {
        if (! isDir) {
            NSLog(@"There's a plain file at my path");
            return nil;
        }
    }