Automation & Scripting

RSS for tag

Learn about scripting languages and automation frameworks available on the platform to automate repetitive tasks.

Automation & Scripting Documentation

Post

Replies

Boosts

Views

Activity

Manually call App Intent from main app target
I would like to call my App Intent directly from my main app target, in an effort to start a live activity in the background when I receive a silent push notification from the server. I have seen in one of the WWDC developer lounges on Slack that this should be possible. Here is how I tried doing it: (it was recommended like that in the lounge) let appIntent = LiveActivityRefreshIntent() Task { try await appIntent() } But I get a compiler error: Instance method 'callAsFunction(donate:)' requires the types '(some IntentResult).Value' and 'Never' be equivalent It's strange because as far as I can tell, I cannot declare my perform method as returning Never. Here is the signature and return value of my App Intent's perform method: func perform() async throws -> some IntentResult { LiveActivityController.shared.updateLiveActivities() return .result() } Is there still a way to call the app intent from my code? If so, how?
0
1
346
Aug ’24
Applescript: window API handler crashing in split view
I've a simple Applescript script as following: tell application "Terminal" -- Get the current tab set currentTab to selected tab of first window -- Set the current tab's theme to Homebrew set currentTab's current settings to settings set "Homebrew" end tell which works as expected when Terminal is run as a "normal" window, but fails with the following error when in Split View terminal-color.scpt: execution error: Terminal got an error: AppleEvent handler failed. (-10000) Any way to work around this error?
3
0
377
Aug ’24
Moving file to a system folder
When making a custom System Settings panel, I want the project to automatically move the prefpane file to /Library/PreferencePanes/. With Run Script, the build fails because of denial to perform the operation. Sudo doesn't help, too. PREFPANE_SRC="${BUILT_PRODUCTS_DIR}/App.prefPane" PREFPANE_DST="$HOME/Library/PreferencePanes/" echo "PrefPane source path: $PREFPANE_SRC" echo "PrefPane destination path: $PREFPANE_DST" if [ -d "$PREFPANE_SRC" ]; then echo "Installing preference pane to ${PREFPANE_DST}" cp -R "${PREFPANE_SRC}" "${PREFPANE_DST}" else echo "Preference pane not found: ${PREFPANE_SRC}" exit 1 fi
8
0
529
Aug ’24
Add option to finder context menu
Hello! I want to add an option to the finder context menu. In particular the context menu that shows when you right click empty space inside a folder. Its not problem if I have to write some swift code. It must be possible, because Google drive or Dropbox also add options to that menu directly. I do not want to add a option to the Quick options, but just an option that right below the "New folder" option. Is this possible? And can someone point me in the right direction? Maybe some API from apple or something? Thanks!
1
0
299
Aug ’24
My Final Cut Pro extension is not allowed assistive access
I’m building an app extension for Final Cut Pro. It includes a main app that doesn't perform any actions, an extension that handles the code execution, and an export app responsible for uploading the exported file. To assist the user, I’ve added an upload button that triggers an AppleScript. This script exports the current project and then uploads it. The AppleScript simply selects the share option and the appropriate share destination. However, the issue arises when I click the upload button: the app asks the user to grant Automation permission, allowing it to control Final Cut Pro and System Events. After granting this permission, the script proceeds to the AppleScript, but an error occurs, stating: System Events got an error: APP is not allowed assistive access. Is there a permission I'm missing?
0
1
273
Sep ’24
AppIntent with flexible return types
To support AppIntent in our app, we plan to follow the same approach as the “Get Details of Reminders” Shortcut Action in the Reminders app, as recommended in this WWDC session (https://developer.apple.com/wwdc24/10176?time=166). The goal is to allow querying all properties of an entity—referred to as “Node” in our app—using a single, configurable intent. For instance, we want one intent that can query properties like “Title,” “Background Color,” and “Font Name” for a specific node. However, since the returned properties have varying data types, this setup requires flexible return types in the perform implementation of our “Get Details” intent. The challenge is that the AppIntent protocol mandates the use ReturnsValue one associated type as the result of perform. For example, we can use ReturnsValue<String> to retrieve the “Title” property, but this would restrict us from using ReturnsValue<Color> for the “Background Color” property. What’s the best approach for implementing an Intent where the return types vary based on the input parameters provided?
1
0
348
Sep ’24
Modifying AAC/M4A audio file metadata with Shortcuts on macOS
I want to use the Shortcuts app on macOS Monterey to modify M4A/AAC audio file metadata for files that I have ripped from CD to my local Music app library. How can I use a regular expression on track titles to replace text that matches a certain regex pattern? I have already written the regex, I just need help with the Shortcuts app. I've started my shortcut with a "Find Music" action connected to a "Repeat with Each" loop action. Within the loop, I use a "Get Details of Music" action to get the title, which is passed to a "Replace Text" action using my regex. I just don't know how to write the correct new title into the music file's title/name metadata field. I tried a "Rename File" action with type "iTunes media" to try to set the "Title" field, but the field wasn't updated either in the Music app or in the M4A/AAC file itself. I couldn't find any other actions that seemed like they might be able to modify the field. I'd prefer a solution that goes through the Music app / its APIs, rather than directly modifying the M4A on the file system, because the latter would force me to have the Music app scan for changed files after the files we're modified.
0
0
286
Sep ’24
Shortcut action that should return a file deletes the file instead
I have an app intent that returns a file from inside the Sandbox. With iOS 18 RC, the call to INFile results in the file being deleted, instead of the file being returned. intentResponse.file = INFile(fileURL: fileURL, filename: fileName, typeIdentifier: nil) This seems to happen if the file was created by an earlier Shortcut action that calls FileManager().copyItem(), but not for files created by other means. I haven't found a reference in the developer documentation about INFile resulting in the file being deleted. I can block FileManager() from deleting the file by setting its immutable attributes to true, but that prevents me from removing it later.
3
2
437
Sep ’24
WatchOS 11 - Shortcut with SSH script returns "Cannot send with an inactive account"
Hi everyone, I have a shortcut that works great on iOS and on MacOS but that for some reason, doesn't work on WatchOS. The shortcut contains only a "Run script over SSH" item, I've tested both with password and public Key, they work well on the other devices but in WatchOS they shortcut returns "Cannot send with an inactive account". Any idea of what the issue is? Regards, Ade
3
0
394
Sep ’24
script stopped working after upgrade to Sequoia
Hello, I don't know much about AppleScript, but I found this script on a Raycast site that dismisses Notification Center notifications. It worked great on Sonoma but has stopped working in Sequoia. Here is the code: tell application "System Events" tell process "NotificationCenter" if not (window "Notification Center" exists) then return set alertGroups to groups of first UI element of first scroll area of first group of window "Notification Center" repeat with aGroup in alertGroups try perform (first action of aGroup whose name contains "Close" or name contains "Clear") on error errMsg log errMsg end try end repeat -- Show no message on success return "" end tell end tell When using this to attempt to dismiss notifications, it returns the following error: Can’t get scroll area 1 of group 1 of window "Notification Center" of process "NotificationCenter". Invalid index. (-1719) Please help me fix it so it will run in Sequoia! This script was super useful.
1
2
300
Sep ’24
Applescripting Chrome email
Hello all, I need some guidance please. Since recent security changes at Microsoft. AppleMail and Outlook on my very old MacBook (El Capitan) can no longer send/recieve emails as authorisation cannot bind. Before I could automate email (hotmail account) sending with AppleScript. I now use a web mail page for Outlook via Chrome but having to send manually. Can I get some advice on how to control, with AppleScript, the attached webpage to: open a new email add recipient in the To field add a subject attach a file send email. Or is there another solution (apart from buying a newer Mac!). Thank you
2
1
257
Sep ’24
Can an app be seen as a trigger device on Homekit?
Suppose I want to create a dummy switch for HomeKit using an app. I run the app for the first time, the app registers itself as a dummy switch and all accessories see the app as an OFF switch. The following day, I run the app again and turn the dummy switch ON. All accessories that were monitoring the status of that switch, adjusted themselves accordingly, run their automations and so on. Can an app do that in iOS, macOS, iPadOS, watchOS, etc.? If so, can you point me in the right direction?
1
0
263
Oct ’24
Shortcuts Automation Trigger Transaction Timeouts
Description The Shortcut Automation Trigger Transaction frequently times out, ultimately causing the shortcut automation to fail. Please see the attached trace for details. Additionally, the Trigger is activated even when the Transaction is declined. Details In the trace I see the error: [WFWalletTransactionProvider observeForUpdatesWithInitialTransactionIfNeeded:transactionIdentifier:completion:]_block_invoke Hit timeout waiting for transaction with identifier: <private>, finishing. Open bug report: FB14035016
0
0
273
Oct ’24
Shortcuts app in macOS has no logic
I'm trying to study music theory and I need a simple series of tasks to be automated to avoid wasting time on repetitive actions. That's what the Shortcuts app is for, but the actions it comes with are either severely mislabeled, or just don't work. I tried to ask for this in some regular forums and nobody could give me a simple answer, so I figured this is something that developers probably know. I just need four PDFs to open in Preview, their windows moved to one of my monitors, and then be tiled in four equal sizes, with the order determined by me. Sounds easy, doesn't it? But I've been trying to accomplish this for over a year in Shortcuts and even Automator, but at best I can get halfway there. I've also noticed that the Shortcuts I had prepared are running awfully slow. I'm on a Mac Studio M1 Ultra, and these PDFs are less than 10 MB each, three of them are less than 5 MB. These used to open almost instantly, but now the first one opens, then 3-5 seconds later the next one opens and so on. As for the window tiling, at best it's tiling three of the windows correctly, but the other one that should tile on the top left, doesn't resize to the quarter of the screen. But worst of all, they are supposed to move to one of the monitors and do the tiling there, but they all open and tile on the main monitor. So this is one I started today from scratch: Logically speaking, this should work. But either I'm not following the logic with which Shortcuts was designed, or Shortcuts just doesn't work very well. I'm hoping it's just that I don't follow the logic, but the help is not very helpful. It's rather scant, and other than that, I can't find something that will give me more information about how it works. I'm on the current version of Sonoma, but this was the same in the previous macOS. I doubt it changed at all in Sequoia. Sorry if I'm asking this in a developer forum, but I figured it's the place where I can finally get some answers after over a year of trial and error and online searching and getting nowhere.
3
0
324
Oct ’24
Run Application In The Background Automation
I’ve developed an automation and shortcut using the iPhone Shortcuts app in IOS 18, something that hasn’t been done before. With support from Apple’s customer service, I was encouraged to bring this idea to life. The automation’s purpose is to open a specified iOS app, move it to the background, and use a txt database in Folders to ensure uninterrupted data flow and continuous connectivity—especially useful for health apps where wearable devices need consistent, uninterrupted operation and monitoring (e.g., doctor tracking or wearable device connectivity). I would like to share the Automation and the Shortcut with the community.
2
0
236
Oct ’24
Correctly using NSAppleScript for Mail.app plugin
Context I'm working on a Mail.app plugin. I would like to disseminate plugin via AppStore. I'm interested in exposing a functionality to user enabling user to choose if plugin should apply to all or selected email account. My intention is to use AppleScript to get a list of available email accounts and expose the list to the end-user via SwiftUI Sourcing account information Apple Script I'm using the following AppleScript tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell The above generates expected results when executed using Script Editor. Swift Implementation This is still incomplete but shows the overall plan. // // EmailAccounts.swift import Foundation enum EmailScriptError: Error { case scriptExecutionError(String) } struct EmailAccounts { func getAccountNames() -&gt; [String]? { let appleScriptSource = """ tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell """ var error: NSDictionary? var accountNames: [String] = [] // Create script object, exit if fails guard let scriptObject = NSAppleScript(source: appleScriptSource) else { return nil } // Execute script and store results, nil on error let scriptResult = scriptObject.executeAndReturnError(&amp;error) if error != nil { return nil } // Iterate over results for index in 0...scriptResult.numberOfItems { if let resultEntry = scriptResult.atIndex(index) { if let resultString = resultEntry.stringValue { // Process result handling // accountNames.append(resultString) } } } return accountNames } } Questions Most important one, can I deploy the App on the App Store and use NSAppleScript as shown above? If yes can I use the script in the manner shown above or will I need to store the script in User &gt; Library &gt; Application Scripts location and source it from there. This is outlined in the Scripting from a Sandbox article by Craig Hockenberry, which I cannot link due to being hosted within a not-permitted domain. If yes what entitlements I need to give to the target. I understand that I wouldn't be able to use ScriptingBridge, which feels more robust but wouldn't permit me to deploy the app on the AppStore. My key objective is to programatically identify mail accounts available to Mail.app, if there is a wiser / easier way of doing that I would be more than receptive.
2
0
280
Oct ’24
AppleScript to Automate Envelope Printing
I have a VBScript routine to print envelopes by automating Word. This works just fine. Now I'm trying to do the same thing with AppleScript, also using the Word application. Here is what I have so far: set recipientAddress to text returned of (display dialog "Enter the recipient's address:" default answer "") -- Prompt for recipient city, state, and zip set recipientCityStateZip to text returned of (display dialog "Enter the recipient's city, state, and zip:" default answer "") -- Combine all address parts into a full address set fullAddress to recipientName &amp; return &amp; recipientAddress &amp; return &amp; recipientCityStateZip -- Create a new Word document and print the envelope set dialogResult to display dialog "To print envelope for:" &amp; return &amp; return &amp; recipientName &amp; return &amp; recipientAddress &amp; return &amp; recipientCityStateZip &amp; return &amp; return &amp; "Center envelope upside-down in printer with flap on left" &amp; return &amp; return &amp; "Continue?" buttons {"Yes", "No"} default button 2 with icon caution if button returned of dialogResult is "Yes" then tell application "Microsoft Word" set wdDoc to make new document -- Print the envelope with the collected recipient address and hard-coded return address -- wdDoc's print out envelope(address:fullAddress, returnAddress:returnAddress) -- Close the document without saving close wdDoc saving no end tell end if What does NOT work is the commented line near the end of the script which starts with -- wdDoc's print out envelope... Either I am doing it wrong, or Word for Mac can't be automated that way. Can anyone help with this script, or at least suggest a different method to print an envelope on demand? Thanks...
1
0
194
Oct ’24