TweetFollow Us on Twitter

Introduction to Scripting iCal

Volume Number: 21 (2005)
Issue Number: 11
Column Tag: Programming

AppleScript Essentials

Introduction to Scripting iCal

by Benjamin S. Waldie

For the past couple of articles, I have discussed scripting specific applications. By now, you should be starting to realize AppleScript terminology varies from application to application. Some applications don't support AppleScript at all, some are more scriptable than others, some have more confusing terminology, etc. Even as become more knowledgeable as a scripter, you will find that there is a learning curve whenever you need to script a new application. Browsing the application's dictionary, and any accompanying documentation or example scripts is usually your best bet for learning how to script a new application.

This month, I will continue to discuss application-specific scripting, and this time, I will focus on iCal. Please note that all sample code within this article was written and tested with Mac OS X Tiger 10.4.x. Many times, software updates will introduce changes in the AppleScript terminology of a given application or process. Therefore, if you are using an older system, some code may not work properly, or may need to be adjusted slightly to work on your machine.

Working with Calendars

Let's begin by discussing the highest-level class within iCal's object hierarchy, a calendar. In iCal, a calendar contains events and to do's, which we will discuss a little later. For now, let's talk about creating calendars, locating them, and more.

Making a New Calendar

More than likely, you are working with existing calendars within iCal, such as a "Home" or "Work" calendar. However, should you need to, you do have the ability to create calendars via AppleScript.

iCal actually contains a command specifically for creating calendars, called simply enough create calendar. This command has an optional parameter, which will allow you to specify the calendar's name. The following sample code demonstrates the creation of a calendar with the use of this command.

tell application "iCal"
   create calendar with name "My Calendar"
end tell

One thing to take note of when using this command is that it does not produce a result. Because of this, you cannot place the newly created calendar into a variable for future reference. As an alternative to the create calendar command, you can also use the make command. This may be a better choice in this situation, as the make command does produce a result, that result being the newly created item. For example, the following code demonstrates how the make command can be used to create a calendar. In this example, the result of this command - the newly created calendar - is placed into a variable called theCalendar, which I can now reference later in my script.

tell application "iCal"
   set theCalendar to make new calendar with properties {title:"My Calendar"}
end tell
--> calendar 3 of application "iCal"

Getting a List of Calendars

If you are working with existing calendars, you may need to write code that will retrieve a list of these calendars. The following code demonstrates how to retrieve a list of all existing calendars.

tell application "iCal"
   set theCalendars to every calendar
end tell
--> {calendar 1 of application "iCal", calendar 2 of application "iCal", 
   calendar 3 of application "iCal"}

The previous code will return references to your existing calendars. However you , may only need to retrieve the names of your calendars. To do this, simply retrieve the title of every calendar. For example:

tell application "iCal"
   set theCalendarNames to title of every calendar
end tell
--> {"Home", "Work", "My Calendar"}

Changing Calendar Views

Within iCal, you have the option to view calendars in several different ways. You can use scripting to change calendar views as well. The following example code demonstrates how to change the calendar view to display in day view mode.

tell application "iCal"
   switch view to day view
end tell

The following sample code demonstrates how to change the calendar view to display in week view mode.

tell application "iCal"
   switch view to week view
end tell

The following example code demonstrates how to change the calendar view to display in month view mode.

tell application "iCal"
   switch view to month view
end tell

So, with the use of the code above, you can actually customize the viewing experience of iCal for the user, as your script processes.

Subscribing to a Calendar

In addition to creating calendars, you can also write code to subscribe to a calendar, using a calendar URL. The following code demonstrates how this is done.

tell application "iCal"
   GetURL "webcal://ical.mac.com/ical/DVDs.ics"
end tell

Please note that, when subscribing to a calendar via AppleScript, some manual intervention will be required. iCal will pop up a few dialogs, allowing users to confirm that they actually do want to subscribe to the calendar, and also allowing them to configure subscription settings. See figure 1.


Figure 1. Calendar Subscription Dialog

Working with Events and To Do's

Now that we have discussed calendars, let's talk about elements of calendars. Specifically, we will walk through several tasks involving events and to do's.

Making a New Event

Like calendars, events can be created with AppleScript. To do this, use the make command. When creating an event, you will most likely want to specify values for various attributes of that event. For example, for an event, you may want to specify the event's name, description, location, etc. This can be done as the event is created, with the use of the with properties parameter. The following sample code demonstrates how to create a new all-day event for the current day, with a specified name, description, and location.

tell application "iCal"
   tell calendar "My Calendar"
      set theDate to current date
      make new event at end with properties {description:"Event Description", 
         summary:"Event Name", location:"Event Location", start date:theDate, 
         allday event:true}
   end tell
end tell
--> event 1 of calendar 3 of application "iCal"

To create an event that falls within a specific time period, you may specify the start date and end date properties of the event. For example, the following example code will create an event at the current date and time, with a length of 2 hours.

tell application "iCal"
   tell calendar "My Calendar"
      set theCurrentDate to current date
      make new event at end with properties {description:"Event Description", 
         summary:"Event Name", location:"Event Location", start date:theCurrentDate, 
         end date:theCurrentDate + 120 * minutes}
   end tell
end tell
--> event 1 of calendar 3 of application "iCal"

Making a New To Do

The process of creating a to do is virtually the same as that of creating an event. Again, you can use the make command, and you may optionally specify properties to be applied as the to do is created. The following sample code will create a to do with a specified summary, description, and due date.

tell application "iCal"
   tell calendar "My Calendar"
      set theDueDate to (current date) + 30 * days
      make new todo at end with properties {description:"To Do Description", 
         summary:"To Do Name", due date:theDueDate}
   end tell
end tell
--> todo 1 of calendar 3 of application "iCal"

To find a complete list of event and to do properties, consult the appropriate class in the iCal suite in iCal's AppleScript dictionary.

Finding an Event or To Do

Many times, you may be working with existing events or to dos. If this is the case, then you might need to locate the appropriate event or to do in some way. The best way to locate something in iCal is to do so by its unique ID. In iCal, calendars, events, and to do's all have unique ID's, which can be retrieved by AppleScript from the item's uid property. The following sample code demonstrates how to retrieve the ID of an event.

tell application "iCal"
   tell calendar "My Calendar"
      set theEvent to first event
      return uid of theEvent
   end tell
end tell
--> "1BCA3512-F3A9-4BCB-A0FD-BE812968D371"

If you have the ID of an event or to do, you can then find the item by its ID. The following code shows how to locate an event by its unique ID.

tell application "iCal"
   tell calendar "My Calendar"
      set theEvent to first event whose uid = "1BCA3512-F3A9-4BCB-A0FD-BE812968D371"
   end tell
end tell
--> event 1 of calendar 3 of application "iCal"

This same technique may be used to locate a to do by its unique ID.

Viewing an Event or To Do

AppleScript can also be used to display a specific event or to do within iCal. To do this, use the show command, and specify the item that you want to display. For example, the following sample code will cause iCal to display and select a specific event, which, in this case, is stored in a variable named theEvent.

tell application "iCal"
   tell calendar "My Calendar"
      show theEvent
   end tell
end tell

Deleting an Event or To Do

Just as you can create events and to do's in iCal, you can also delete them. To delete an item in iCal, use the delete command and specify the item that you want to delete. For example, the following code will delete a specified event that is stored in a variable.

tell application "iCal"
   tell calendar "My Calendar"
      delete theEvent
   end tell
end tell

Working with Alarms

If you are an avid iCal user, then you are probably already aware that events and to do's can be configured with alarms. There are multiple types of alarms that you can configure manually, which can also be configured via scripting. AppleScript can be used to create the following types of alarms:

  • Display Alarm - This type of alarm will display a message to the user, letting the user know about a scheduled event or to do. With the use of scripting, you can set the trigger interval or date for this type of alarm.
  • Mail Alarm - This type of alarm will send an email message to the current user, notifying the user of an upcoming event or to do. Like a display alarm, the trigger date or interval for this type of alarm may be set via scripting.
  • Open File Alarm - This type of alarm will open a file at a specified time. AppleScript can be used to set the date or interval for the alarm. It can also be used to specify the path to the file that should be opened. An alarm of this nature can be extremely useful if you want a script to trigger at a specific time.
  • Sound Alarm - This type of alarm will produce an audio alert about an upcoming event or to do. For this type of event, AppleScript may be used to specify the date or interval, as well as the name or file path of a sound to be used for the alert.

Adding an Alarm to an Event or To Do

Let's take a moment to look at how an alarm can be created with the use of AppleScript, for a given event or to do. For this first example, we are going to create a display alarm. The following example code will add a display alarm to a specified event.

tell application "iCal"
   tell calendar "My Calendar"
      set theEvent to event 1
      tell theEvent
         make new display alarm at end with properties {trigger interval:-30}
      end tell
   end tell
end tell
--> display alarm 1 of event 1 of calendar 3 of application "iCal

In the code above, you will notice that the trigger interval property of the event is set to -30. The trigger interval property may be specified to configure when the alarm message should be displayed. This property should be given a numeric value, signifying minutes. In this case, I have specified a negative value of 30. This will cause the alarm to trigger 30 minutes prior to the start date of the event.

Optionally, I can choose to specify a trigger date for the alarm, rather than a trigger interval. This will allow me to configure the alarm to trigger at a specific date and time, rather than on a trigger interval. The following sample code will create a new display alarm for a given event.

tell application "iCal"
   tell calendar "My Calendar"
      set theEvent to event 1
      set theDate to (current date) - 3 * days
      tell theEvent
         make new display alarm at end with properties {trigger date:theDate}
      end tell
   end tell
end tell
--> display alarm 1 of event 1 of calendar 3 of application "iCal"

Let's look at another type of alarm. This time, let's add an open file alarm to an event. For this type of alarm, in addition to specifying a trigger interval or date, we can specify a file path for the item to be opened. The following example code demonstrates the process of creating an open file alarm for a given event.

set theFile to choose file
tell application "iCal"
   tell calendar "My Calendar"
      set theEvent to event 1
      set theDate to (current date) - 3 * days
      tell theEvent
         make new open file alarm at end with properties {trigger date:theDate, 
            filepath:theFile}
      end tell
   end tell
end tell
--> open file alarm 1 of event 1 of calendar 3 of application "iCal"

If you look in iCal's dictionary, you may notice that the filepath property of an open file alarm is defined as needing a POSIX style path. As you can see from the code above, if you pass an AppleScript alias reference, that will work as well. To pass a POSIX path, you may need to convert the desired file's path. For example:

set theFile to POSIX path of (choose file)
--> "/Users/bwaldie/Desktop/FileToOpen.scpt"

Please note that if you configure an open file alarm to open a compiled AppleScript file, the script will actually be loaded and run by iCal, rather than simply opened. See figure 2. This is a great way to create a workflow with scripts that trigger at scheduled intervals.


Figure 2. An Open File Alarm to Trigger a Compiled Script

Triggering Scripts and Automator Workflows from iCal

As we have seen above, there are ways to trigger an AppleScript from within iCal. You can quickly and easily create events, and add open file alarms to run compiled scripts, open script applications, etc.

You can also trigger Automator workflows from iCal, and Automator makes the process of configuring such scheduled events a snap. First, begin by creating an Automator workflow to perform any set of desired tasks. Next, select Save as Plug-In... from the File menu within Automator. From the plug-in type popup menu, select iCal Alarm. See figure 3.


Figure 3. Creating an Automator iCal Alarm Plug-In

Click the Save button, and a new event will be created in iCal, which will be configured to trigger the workflow. Now, you can adjust the event, as needed, perhaps putting it on a repeating schedule. See figure 4 for an example of a configured event.


Figure 4. A Configured Automator iCal Alarm Plug-In Event

In Closing

Hopefully, you are already thinking of the great possibilities for creating scripts that interact with iCal, or that work in conjunction with iCal. In addition to creating and interacting with calendars, events, and to do's, you can also begin to schedule the execution of your scripts, allowing you to really begin putting your computer to work for you, perhaps at night, over the weekend, or whenever you are away from your desk.

For a list of some existing iCal scripts, try searching for "iCal" in the ScriptBuilders section of MacScripter.net at http://scriptbuilders.net/. For more information about creating and scheduling Automator workflows, check out the help files that come with Automator, or check out my Automator book, available from SpiderWorks at http://www.spiderworks.com/ books/automator.php.

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.