macosapplescriptmacbookpro

Fetching contact's birthday in Apple Script


I am trying to fetch the birthday of a contact in the contacts list, on Mac.

tell application "Contacts"
    set firstContact to first person
    set contactName to name of firstContact
    set contactBirthday to birthday of firstContact
end tell

-- Display the information
display dialog "Name: " & contactName & return & "Birthday: " & (contactBirthday as string)

This errors:

tmp.scpt:136:144: execution error: Contacts got an error: Can’t make birthday of person id "0BC1D...48B:ABPerson" into type specifier. (-1700)

How to solve this? The contact has a birthday set indeed.


Solution

  • You will find File:Open Dictionary… in Script Editor invaluable for tracking down this sort of problem. Open the dictionary for Contacts and search for “birth” or (because there are a few date fields built into the system) “date”.

    Script Editor Dictionary view for Contacts, searcing on “birth”.

    In this case the solution is a simple one: the name of the property isn’t birthday but rather birth date. Change birthday to birth date and your script works.

    tell application "Contacts"
        set firstContact to first person
        set contactName to name of firstContact
        set contactBirthday to birth date of firstContact
    end tell
    
    -- Display the information
    display dialog "Name: " & contactName & return & "Birthday: " & (contactBirthday as string)
    
    

    You may also find it useful to use Script Editor for testing thorny problems like this, even when your end result will be a command-line script or a snippet of code in another application. In this example, while the error text remains somewhat obscure, Script Editor will helpfully highlight the offending code.

    Script Editor highlights the code where the error occurred.

    The word “birthday” is very helpfully highlighted: that’s where Script Editor thinks the error occurred. If you look closely you can also see that valid properties (in this example, name) are displayed using a different color than other parts of the code. Script Editor is very useful for testing AppleScript code when the code can be broken into small parts.