Search code examples
objective-cswiftmacoscocoashutdown

Identifying if the application is terminating because the system is shutting down


I am trying to convert these lines in Objective-C to swift

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender  
{  
   ...  
    NSAppleEventDescriptor* appleEventDesc = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];  
    NSAppleEventDescriptor* whyDesc = [appleEventDesc attributeDescriptorForKeyword:kEventParamReason];  
    OSType why = [whyDesc typeCodeValue];  
    if (why==kAEShutDown || why==kAERestart || why==kAEReallyLogOut)  

they will detect if the app is terminating due to the system shutting down.

I am unable to convert this line

if (why==kAEShutDown || why==kAERestart || why==kAEReallyLogOut)  

I guessed something like

    let codeValue = whyDescription?.typeCodeValue

if ((codeValue == AEKeyword(kAEShutDown)) ||
    (codeValue == AEKeyword(kAERestart)) ||
    (codeValue == AEKeyword(kAEReallyLogOut))) {

Is this correct?

or should it be

if ((codeValue == OSType(kAEShutDown)) ||
    (codeValue == OSType(kAERestart)) ||
    (codeValue == OSType(kAEReallyLogOut))) {

Xcode is compiling it fine, but I am not sure if kAEShutDown, kAERestart, and kAEReallyLogOut are `AEKeywords that can be used there.

I could find no documentation on that, as expected.


Solution

  • Both AEKeyword and OSType are a typealias to FourCharCode. Technically, they are the same type, therefore it does not matter which you use.

    However, since typeCodeValue is declared as OSType, then OSType is the logical choice.

    Also, it seems the constants are already declared as OSType, therefore there should not be any reason to cast them.