Search code examples
macoscocoacore-datasandbox

How to use hardcoded file path names with sandbox


Ok, yes I know now that you can not use hardcoded paths with sandbox. Up to this point I have not delt with sandbox, so I never encountered it.

I have a Coredata App (Mac OSx) and I used the default save code and the default path location (user/...../applicationsupport/... This, of coarse, is not acceptable in the sandbox.

Without requiring the user to manually open the data file each time the program is launched, is there another way to deal with this?

I would appreciate any input/suggestions.

Thanks You


Solution

  • Sandbox doesn't mean there isn't any access to files and folders without user selection. As it said in App Sandbox in Depth article there's container directory you still having access to.

    For taking a path to your Application Support-directory you should use the same code whenever you use Sandboxing or not.

    + (NSString *)executableName
      {
       NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
       if(!executableName || executableName.length==0)
          return nil;
       return executableName;
      }
    
    - (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
                               inDomain:(NSSearchPathDomainMask)domainMask
                    appendPathComponent:(NSString *)appendComponent
                                  error:(NSError **)errorOut
      {
       NSArray *paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory,domainMask,YES);
       if ([paths count]==0)
          return nil;
       NSString *resolvedPath = [paths objectAtIndex:0];
       if (appendComponent)
          resolvedPath = [resolvedPath stringByAppendingPathComponent:appendComponent];
       NSError *error;
       BOOL success = [self createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES attributes:nil error:&error];
       if (!success)
         {
          if (errorOut)
             *errorOut = error;
          return nil;
         }
       return resolvedPath;
      }
    
    - (NSString *)applicationSupportDirectory
      {
       NSError *error;
       NSString *result = [self findOrCreateDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask
                                  appendPathComponent:[self executableName] error:&error];
       if (error)
          return nil;
       return result;
      }