在Delphi中获取MacOS Application Support文件夹

时间:2017-08-10 16:11:13

标签: macos delphi

Apple表示将存储应用程序状态的文件放在" Application Support"文件夹和"使用应用程序支持目录常量NSApplicationSupportDirectory"

https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW11

Delphi的TPath类方法有各种TPath.GetXXXX(包括TPath.GetLibraryPath,但我找不到一个返回Application支持文件夹。

如何在Firemonkey应用程序中获取Application Support文件夹?

1 个答案:

答案 0 :(得分:2)

硬编码方法(您可能尝试过);由于Application Support文件夹位于Library文件夹下:

uses System.IOUtils;

function GetApplicationSupportDir : string;

begin
   Result := TPath.Combine(TPath.GetLibraryPath,'Application Support');
end;

或者,直接从iOS或OSX中检索它:(对于Delphi XE8及更高版本)

uses
     Macapi.Helpers,
     {$IFDEF iOS}
     iOSapi.Foundation,
     {$ENDIF}
     {$IFDEF OSX}
     Macapi.Foundation,
     {$ENDIF}

     System.IOUtils;

function GetApplicationSupportDir : string;

var
   Paths : NSArray;
   Dir : NSString;

begin
   // For "Application Support" under the User's Library directory:
   Paths := TNSArray.Wrap(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True));

   // For "Application Support" under the System Library directory:
   //Paths := TNSArray.Wrap(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSSystemDomainMask, True));


   Dir := TNSString.Wrap(Paths.objectAtIndex(0));

   Result := NSStrToStr(Dir);
end;

对于XE7,这可能有效:

uses
     Macapi.Helpers,
     {$IFDEF iOS}
     iOSapi.Foundation,
     {$ENDIF}
     {$IFDEF OSX}
     Macapi.Foundation,
     {$ENDIF}

     System.IOUtils;

///////////////////////////// Added since XE7:

const
   _PU = '_';
   libFoundation = '/System/Library/Frameworks/Foundation.framework/Foundation';

type
   NSUInteger = LongWord;
   NSSearchPathDirectory = NSUInteger;
   NSSearchPathDomainMask = NSUInteger;

function NSSearchPathForDirectoriesInDomains(directory: NSSearchPathDirectory; domainMask: NSSearchPathDomainMask;
  expandTilde: Boolean): Pointer {NSArray}; cdecl;
  external libFoundation name _PU + 'NSSearchPathForDirectoriesInDomains';

/////////////////////////////

function GetApplicationSupportDir : string;

var
   Paths : NSArray;
   Dir : NSString;

begin
   // For "Application Support" under the User's Library directory:
   Paths := TNSArray.Wrap(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True));

   // For "Application Support" under the System Library directory:
   //Paths := TNSArray.Wrap(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSSystemDomainMask, True));

   Dir := TNSString.Wrap(Paths.objectAtIndex(0));

   Result := NSStrToStr(Dir);
end;