Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Delphi disable AppNap on MacOSX application

Digital Innovation Partner

Delphi disable AppNap on MacOSX application

Apple MacOSX is a fantastic OS, when your app goes in the background it consumes few resources, this is a fantastic thing if you do not plan to run processes in the background or if it is not a server application.

To avoid that your application is not slowed down I have created a very simple delphi unit that you can add to your projects where you have this need.

unit Macapi.Foundation.ext;

interface
uses Macapi.ObjCRuntime, Macapi.ObjectiveC, Macapi.CocoaTypes,
Macapi.CoreFoundation, Macapi.CoreServices,Macapi.Foundation;

type

NSProcessInfoExt = interface(NSProcessInfo)
['{1458E7B6-B64E-430E-8DE4-A19C680C17D3}']
// add process begin
// Added following
function beginActivityWithOptions(options: NSActivityOptions; reason: NSString): NSObject; cdecl;
end;
TNSProcessInfoExt = class(TOCGenericImport<NSProcessInfoClass, NSProcessInfoExt>)
public
class procedure disableAppNap(Areason : String = 'Your reason to disable appNap');
end;

var
ProcessInfo: NSProcessInfoExt;

implementation

{ TNSProcessInfoExt }

class procedure TNSProcessInfoExt.disableAppNap(Areason: String = 'Your reason to disable appNap');
const
NSActivityBackground = 255;
NSActivityIdleSystemSleepDisabled = 1048576;
NSActivityUserInitiated = NSActivityIdleSystemSleepDisabled or 16777215;
NSActivityLatencyCritical = 1095216660480;

type
NSActivityOptions = UInt64;
var
obj: NSObject;
reason: NSString;
options: NSActivityOptions;
begin
reason := NSSTR(Areason);
options := NSActivityUserInitiated or NSActivityLatencyCritical;
obj := TNSProcessInfoExt.Wrap(TNSProcessInfo.OCClass.processInfo).beginActivityWithOptions(options, reason);

ProcessInfo := TNSProcessInfoExt.Wrap(TNSProcessInfo.OCClass.processInfo);
ProcessInfo.beginActivityWithOptions(NSActivityUserInitiated or NSActivityLatencyCritical,reason);

end;

end.

So to prevent your application from being put into appNap, simply add the following call when creating the main form:

procedure TfrmProject.FormCreate(Sender: TObject);
begin
  {$IFDEF MACOS}
    TNSProcessInfoExt.disableAppNap('Maintain web server active');
  {$ENDIF}
end