How to use hardcoded file path names with sandbox

瘦欲@ 提交于 2020-04-05 06:26:35

问题


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


回答1:


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;
  }


来源:https://stackoverflow.com/questions/28205089/how-to-use-hardcoded-file-path-names-with-sandbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!