How to use hardcoded file path names with sandbox

前端 未结 1 1407
面向向阳花
面向向阳花 2020-12-21 19:18

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 Ap

1条回答
  •  有刺的猬
    2020-12-21 19:34

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

    0 讨论(0)
提交回复
热议问题