Search code examples
applescript-objc

How to get the return value of a clicked button using NSAlert


I am using the following:

tell current application's NSAlert's alloc's init()
  its setMessageText:"Alert test"
  its setInformativeText:"This is a test"
  its setAlertStyle:2
  its setShowsSuppressionButton:true
  its addButtonWithTitle:"Cancel"
  its addButtonWithTitle:"Replace"
  its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
end tell

I would like to know how do I get the value of the clicked button including "Suppression Button". thanks advance!


Solution

  • Using the NSAlert+MyriadHelpers category from Myriad Helpers, you can use the showOverWithSuppress:calling: method. Using Xcode’s default AppleScript application project and adding the category .h and .m files to it, an example would be something like:

    property suppressed : false
    
    on applicationWillFinishLaunching:aNotification
        tell current application's NSUserDefaults's standardUserDefaults
            its registerDefaults:{SuppressAlert:suppressed}
            set my suppressed to its objectForKey:"SuppressAlert"
        end tell
        set state to ""
        if not suppressed then set state to "not "
        set response to (display dialog "Example alert is currently " & state & "suppressed." buttons {"Clear", "Set", "Continue"} default button 3)
        if button returned of response is "Set" then
            set my suppressed to true
        else if button returned of response is "Clear" then
            set my suppressed to false
        end if
        doAlert()
    end applicationWillFinishLaunching:
    
    on doAlert()
        log "performing doAlert() handler"
        if suppressed then return -- skip it
        tell current application's NSAlert's alloc's init()
            its setMessageText:"Alert test"
            its setInformativeText:"This is a test"
            its setAlertStyle:2
            its setShowsSuppressionButton:true
            its addButtonWithTitle:"Cancel"
            its addButtonWithTitle:"Replace"
            its showOverWithSuppress:theWindow calling:"alertDidEnd:"
        end tell
    end doAlert
    
    on alertDidEnd:response
        set buttonName to (first item of response) as text
        if buttonName = "Cancel" then display alert "Cancel button clicked!"
        set my suppressed to (second item of response) as boolean
    end alertDidEnd:
    
    on applicationShouldTerminate:sender
        tell current application's NSUserDefaults's standardUserDefaults
            its setObject:suppressed forKey:"SuppressAlert" — update
        end tell
        return current application's NSTerminateNow
    end applicationShouldTerminate: