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

Adobe Animate CC 2020 20.0.1 - Animation...
Animate CC 2020 is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous Flash Professional customer). Animate CC 2020 (was Flash CC) lets you... Read more
Adobe Acrobat DC 19.021.20058 - Powerful...
Acrobat DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat DC with Adobe Document Cloud services is... Read more
Adobe Acrobat Reader 19.021.20058 - View...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more
Adobe Flash Player 32.0.0.303 - Plug-in...
Adobe Flash Player is a cross-platform, browser-based application runtime that provides uncompromised viewing of expressive applications, content, and videos across browsers and operating systems.... Read more
Adobe InDesign CC 2019 15.0.1 - Professi...
InDesign CC 2019 is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous InDesign customer). Adobe InDesign CC 2019 is part of Creative Cloud.... Read more
Adobe Lightroom Classic 9.1 - Import, de...
You can download Lightroom for Mac as a part of Creative Cloud for only $9.99/month with Photoshop, included as part of the photography package. The latest version of Lightroom gives you all of the... Read more
Shredo 1.2.7 - $6.99
Shredo is a beautiful, functional file-shredding and privacy scan utility. It permanently shreds files, folders, and external volumes' contents to keep information secure and impossible for anyone to... Read more
Visual Studio Code 1.41.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
calibre 4.6.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Deeper 2.5.1 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more

Latest Forum Discussions

See All

Abyssrium Pole is an upcoming aquarium b...
FleroGames' upcoming Abyssrium Pole has recently hit one million pre-registers, which is very impressive, particularly for a fairly casual looking game. Those who have pre-registered will receive 1000 Pearl when the game launches on 8th January... | Read more »
Two Spies is pretty fun, but it's h...
Two Spies just dropped on the App Store this week, and it looks pretty neat. The game has two players capturing various cities across Europe, with the goal of eventually spotting and striking the other spy down. It may be simple-looking, but after... | Read more »
Two Spies is a turn-based game for iOS t...
There aren't too many games that feature pass and play multiplayer and there are even less where you can only play against people you know, even when playing online. But Two Spies does both of those things and you can get it for iOS right now. [... | Read more »
Solve your way through new low-poly puzz...
The best escape-the-room games don’t just test your creative problem-solving skills – they look great, too. Released in October this year by Antler (the developer of the succesful VR puzzle SVRVIVE: The Deus Helix), Krystopia offers everything you... | Read more »
Get ready for an epic adventure with Pea...
Following a hugely successful pre-registration campaign, Pearl Abyss' much-hyped MMORPG, Black Desert Mobile, has finally arrived for iOS and Android. With some of the most impressive visuals on mobile, a vast open world to explore, an in-depth... | Read more »
Elder Scrolls: Blades has ditched chest...
Elder Scrolls: Blades started out as one of the most hyped mobile games of 2019, boasting some impressive visuals and no shortage of promise. Our hopes were somewhat dashed when it eventually launched and we all became privy to its mishandled... | Read more »
Hands-On with the Pocket City December U...
At the end of last month, Codebrew Games announced an update coming to their popular city-builder, Pocket City some time this month. In this update is the promise of expanding your city out into other regions, enacting policies, and more. The full... | Read more »
Black Desert Mobile is available for pre...
Pearl Abyss' stunning open-world MMORPG, Black Desert Mobile, is set to launch for iOS and Android on December 11th at 12 AM PST (8 AM UTC). However, those looking to get in early and test out the in-depth character customisation will be able to... | Read more »
Extraordinary Ones, NetEase's innov...
NetEase's inventive 5v5 anime MOBA, Extraordinary Ones, has now opened for pre-registration ahead of its global launch in early 2020. The game seems to have received a fairly warm reception from fans after its soft-launch earlier in the year,... | Read more »
Dragon Raja is an upcoming MMORPG that b...
Dragon Raja is an upcoming MMORPG from Zulong Games. It’s proven to be an extremely popular title over in China. It’s set in a very cool-looking Cyberpunk world that oozes style. It’s now available for pre-register on Android. [Read more] | Read more »

Price Scanner via MacPrices.net

Find the best Holiday 2019 prices on Apple’s...
Our Apple award-winning price trackers are the best place to look for the best deals and lowest prices on Apple gear this 2019 Holiday shopping season. Scan our price trackers for the latest... Read more
13″ 2.4GHz/256GB Silver MacBook Pro on sale f...
Amazon has the Silver 13″ 2.4GHz/256GB 4-Core Touch Bar MacBook Pro on sale for $1499.99 shipped. Their price is $300 off Apple’s MSRP, and it’s the lowest price currently available for a 13″ 2.4GHz... Read more
Sams Club one day sales event December 14th:...
Through midnight Saturday night (December 14th), Sams Club online has several Apple Watch Series 5 models on sale for $40 off MSRP as part of their One Day sales event. Choose free shipping or free... Read more
Total Wireless offers iPhone 6S models for as...
Total Wireless has Apple 32GB iPhone 6S models available starting at $99: – 32GB iPhone 6S: $99.99 – 32GB iPhone 6S Plus: $149.99 A no-contract Total Wireless prepaid plan is required with your... Read more
Get a 4 or 6-core Mac Mini for up to $170 off...
B&H Photo has 4-Core and 6-Core Mac minis on sale for up to $170 off Apple’s standard MSRP as part of their Holiday 2019 sale. Overnight shipping is free to many US addresses: – 3.6GHz Quad-Core... Read more
Amazon restocks base 13″ 1.4GHz MacBook Pro f...
Amazon has restocked the base 13″ 1.4GHz/128GB Space Gray MacBook Pro for $1099.99 shipped. Their price is $200 off Apple’s MSRP, and it’s the cheapest price available for a new MacBook Pro. Amazon... Read more
Use your Apple Education discount this Holida...
Purchase a new Mac this Holiday 2019 season using Apple’s Education discount, and take up to $400 off MSRP. Purchase an iPad, and take up to $50 off MSRP. All teachers, students, and staff of any... Read more
Apple offers 27″ iMacs for up to $350 off MSR...
Apple has Certified Refurbished 2019 27″ iMacs available starting at $1529 and up to $350 off the cost of new models. Apple’s one-year warranty is standard, shipping is free, and each iMac features a... Read more
Get last year’s 13″ MacBook Air for only $849...
Apple has restocked Certified Refurbished 2018 13″ MacBook Airs starting at only $849. Each MacBook features a new outer case, comes with a standard Apple one-year warranty, and is shipped free. The... Read more
Apple offers a full line of refurbished iPad...
Apple has Certified Refurbished 11″ and 12.9″ iPad Pros available on their online store for up to $250 off the cost of new models. Prices start at $679. Each iPad comes with a standard Apple one-year... Read more

Jobs Board

*Apple* Engineering Specialist (ITC ) - Gene...
…Suitability clearance, per contract requirements. Currently, we are seeking an Apple Engineering Specialist in Washington, DC The responsibilities for candidates in Read more
Senior *Apple* Endpoint Engineer - Leidos (...
…Medicaid Service (CMS) End User environment. Perform specific duties as an Apple Endpoint Engineer in support of the infrastructure operations, hardware, software Read more
Perioperative - RN - ( *Apple* Hill Surgical...
Perioperative - RN - ( Apple Hill Surgical Center) Tracking Code 59281 Job Description Monday - Friday - Part Time - Days Possible Saturdays General Summary: Under Read more
Lead DevOps Engineer - *Apple* - Theorem, L...
Job Summary Apple is looking for a seasoned Lead DevOps Engineer that can lead multiple projects and teams while delivering high quality and performant solutions in Read more
*Apple* Computing Professional - Best Buy (U...
**750013BR** **Job Title:** Apple Computing Professional **Job Category:** Store Associates **Store NUmber or Department:** 000524-Naples-Store **Job Description:** Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.