Weakman10122 Weakman10122 - 1 month ago 12
Objective-C Question

iOS: Is this the proper way to create a directory in Application Support to store my SQL file?

I have a sqlite file that I am trying to store in Application Support Folder. I am using the following code to create the directory.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSError *err;
NSString *dataPath = [applicationSupportDirectory stringByAppendingPathComponent:@"/Email"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&err]; //Create folder

NSString *dataBasePath = [applicationSupportDirectory stringByAppendingString:@"/Email/Email.sqlite"];


This is the printed result when I NSLog dataBasePath


/var/mobile/Containers/Data/Application/8A40E5A9-EEE6-46EF-B71F-36C9A00D5996/Library/Application
Support/Email/Email.sqlite


Is this correct way of creating the directory to store my sql file in Application Support? I have to use Application Support so the user can't mess with it (I use file share so document directory is out of the question) and the OS shouldn't be able to mess with it either. I just need to be sure

Answer

It's close but not quite right. Don't put the / before Email. You want to pass YES to withIntermediateDirectories. And the final path should use dataPath and stringByAppendingPathComponent.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSString *dataPath = [applicationSupportDirectory stringByAppendingPathComponent:@"Email"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
    NSError *err;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&err]) { //Create folder
        NSLog(@"Unable to create folder at %@: %@", dataPath, err);
    }
}

NSString  *dataBasePath = [dataPath stringByAppendingPathComponent:@"Email.sqlite"];