Ben Close
Ben Close

Reputation: 45

How to prevent application from crashing when display goes to sleep in Apple Script

How can I prevent an Apple Script application from crashing whenever the computer logs out or goes to sleep?

I'm currently working on an application that sets the desktop background to the album art of the current song playing in iTunes, however if I put my display to sleep, iTunes will continue to play music but my application will crash, meaning that the desktop background is no longer updating when I return to the computer.

This is the code I'm using to set the wallpaper:

        tell desktop 2
            set picture to fileName
        end tell

where fileName is name of the iTunes artwork of the current song, which has been extracted and saved to the desktop.

It says desktop 2 as I have two different applications for each screen, and conduct testing on my 2nd screen.

This is the error I get when running in Automator and putting the display to sleep:

The action “Run AppleScript” encountered an error.
System Events got an error: Can’t get desktop 2. Invalid index.

I am getting the same results on my primary display also.

How can I stop this script from encountering an error when the display is asleep?

Any suggestions would be greatly appreciated, as I'd love anyone who wants it to have this application.

Upvotes: 2

Views: 105

Answers (1)

vadian
vadian

Reputation: 285250

The safest way is to check if the item exists

if exists desktop 2 then
  tell desktop 2
    set picture to fileName
  end tell
end if

or wrap the code in a try block which ignores any error.

try
  tell desktop 2
    set picture to fileName
  end tell
end try

Upvotes: 0

Related Questions