Shortcuts

RSS for tag

Help users quickly accomplish tasks related to your app with their voice or with a tap with the Shortcuts API.

Posts under Shortcuts tag

108 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Shortcuts App Intent Only for Active Subscribers
I have a Shortcuts action via an App Intent that I want only for active subscribers to use. I have a shared class that handles all the subcription related things. But for some reason my code only works if the app is active in the background. Once the app is quitted and the user performs the Shortcut, the not subscribed error is thrown – even though the user is subscribed. How can I ensure that my subscription check is done correctly, if the app isn’t open in the background? My Code App Intent excerpt: @MainActor func perform() async throws -> some IntentResult & ReturnsValue<MeterIntentEntity> { // Validate that the user is subscribed. // Cancels action with error message if not subscribed. if SubscriptionManager.shared.userIsSubscribed == false { throw IntentError.notSubscribed } // More Code … // Finish and pass created value as result. return .result(value: something) } Subscription Manager excerpt: class SubscriptionManager: ObservableObject { // A singleton for our entire app to use static let shared = SubscriptionManager() let productIds = ["my_sub1", "my_sub2"] @Published private(set) var availableSubscriptions: [Product] @Published private(set) var purchasedSubscriptions: [Product] = [] public var userIsSubscribed: Bool { return !self.purchasedSubscriptions.isEmpty } init() { // Initialize empty products, and then do a product request asynchronously to fill them in. availableSubscriptions = [] Task { await updatePurchasedProducts() } } @MainActor func updatePurchasedProducts() async { for await result in Transaction.currentEntitlements { do { let transaction = try checkVerified(result) if let subscription = availableSubscriptions.first(where: { $0.id == transaction.productID }) { purchasedSubscriptions.append(subscription) } } catch { Logger.subscription.error("Error loading users user's purchased products.") } } }
1
0
172
1d
"Microphone Recording Fails When Launching App from Shortcut (Error Code 561015905)"
I'm experiencing an issue with microphone recording in my app when launched from a Shortcut. The app works correctly when launched directly, but launching it through the Shortcut results in the "Session activation failed" error (code 561015905). Here's what I've done so far: My app has microphone permission granted. The startRecording function sets the audio session category to .playAndRecord. I've implemented error handling within startRecording to catch the error code. The Shortcut workflow includes an action to launch the app (no explicit microphone permission request within the Shortcut). xcode version - 15.2 iphone ios version - 17.4.1
1
0
114
6h
How can I set app shortcut platter background colour on visionOS?
This is a follow up to my previous post, this time using the visionOS 1.2 simulator and Xcode 15.4. I am trying to set the background colour of my app shortcut platter for the visionOS version using NSAppIconComplementingColorNames but it doesn’t take effect when I check the shortcuts app. I see the built in Music Recognition app has a background colour but I am unable to set one for my app. Please note that this feature is working correctly on iOS. But on visionOS it has no effect and returns a plain background. I noticed the documentation doesn't mention it works on visionOS. But if that's the case how was the music recognition app able to set a colour?
0
0
144
2w
iOS Automation could not run because an internal error occurred
I am developing a shortcut for an application that is currently in production. The shortcut essentially involves opening the application and launching a notification so that the AppDelegate initiates a process to scan NFC tags. To achieve this, I have an AppIntent that overrides the variable openAppWhenRun = true and an AppShortcutsProvider to implement this intent. The problem arises when a user updates to the latest version of the application and tries to implement this shortcut through an automation. The following error appears: "When 'Reader' is detected" encountered an error: The action 'Scan DMA tags' could not run because an internal error occurred. This does not always happen, only on some devices. However, if we uninstall and reinstall the application, it works perfectly. But this is not a viable solution since the application uses a database and data loss from frequent uninstallations is not acceptable. Any solution? I have tried to replicate the error but have been unable to do so. This issue has occurred on both iOS 16 and iOS 17.
0
0
162
2w
Test Finder right-click feature in a desktop app using Swift
I'd like to know how to test behavior in Swift on Desktop that needs to interact with external elements, in my case the Finder. My goal is simple: add an option in the right-click menu of the Finder that will open my application with the selected entry or entries (file or folder) from the Finder. I have thus set the elements NSMenuItem, NSMessage, NSPortName, NSRequiredContext (NSApplicationIdentifier: com.apple.finder) etc. I also created a class FinderService with a function performService having this declaration: func performService(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer&lt;NSString&gt;) { NSLog("performService called!") } And I instantiated my class like this: NSApplication.shared.servicesProvider = FinderService(). However, when I build and launch the application nothing happens, well my application runs fine and the instantiation of the class seems to be correctly called. But when I open my Finder, my action is not displayed in the right-click context menu. And in the logs of my application, no error appears. How can I test this?
0
0
231
May ’24
Apple Shortcuts API URL Dynamic Reaction
I have recently started using apple shortcuts to connect to a server to control a remote device. This remote device replies using JSON and depending on the request, it replies with a different status message. I would like to be able to read the reply in the shortcut and change the icon and/or the colour of the shortcut on the home screen depending on the reply. This could be used for locking a door where the reply indicates if the door is locked/unlocked by way of a closed/open padlock or by changing the background colour of the shortcut.
0
0
117
May ’24
Shortcut doesn't open deep link to the app it belongs to, but widget does
I've created widget that opens app on specific view: .widgetUrl(URL(string: "myapp://Dashboard/SpecialView")) It works alright so i know deep links are working. So after that i created Shortcuts.swift file in my main app and added this: import AppIntents import UIKit @available(iOS 16, *) struct StartRecordingIntent : AppIntent { static var title: LocalizedStringResource = "Special" func perform() async throws -> some IntentResult { let url = URL(string: "myapp://Dashboard/SpecialView") DispatchQueue.main.async { UIApplication.shared.open(url!, options: [:], completionHandler: nil) } return .result() } } This intent created shortcut "Special" in shortcut list, and when run, should open exactly the same view as the widget. But all im getting is error: Failed to open URL myapp://Dashboard/SpecialView: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.myapp" failed." UserInfo={BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x600000dd7960 {Error Domain=FBSOpenApplicationErrorDomain Code=3 "Application com.myapp is neither visible nor entitled, so may not perform un-trusted user actions." I don't understand what i'm doing wrong and why can't i open app from shortcut exactly like widget does
1
1
229
May ’24
Appintent and swiftdata
Hi, I'm new to Swift development and encountering an issue that I believe may be due to an error on my part. I have two questions regarding the following code: import AppIntents import SwiftUI import SwiftData @available(iOS 17.0, *) struct CopiarEventoIntent: AppIntent { @Environment(\.modelContext) private var context @Parameter(title: "Nome do Evento") var name: String @Parameter(title: "Data Inicial") var datai: Date @Parameter(title: "Data Final") var dataf: Date @Parameter(title: "Tipo de Evento") var tipo: String @Parameter(title: "Endereço") var endereco: String @Parameter(title: "Lembrete") var reminder: Bool static var title: LocalizedStringResource = "Adicionar Eventos" static var description = IntentDescription("Copiar Eventos e alterar datas", resultValueName: "Resultado") @MainActor func perform() async throws -> some IntentResult & ProvidesDialog { let calData = CalData(title: name, datei: datai, datef: dataf, tipo: tipo, endereco: endereco,reminder: reminder) context.insert(calData) return .result(dialog: "Evento copiado com sucesso!") } } @available(iOS 15.0, *) struct AppShortcuts: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { AppShortcut( intent: CopiarEventoIntent(), phrases: [ "Copiar Evento" ], shortTitle: "Copiar Evento", systemImageName: "square.and.arrow.down" ) } } @available(iOS 15.0, *) struct ShortcutSelectionView: View { @Environment(\.modelContext) private var context @Query(sort: \CalData.title) private var caldatas: [CalData] @State private var selectedEvent: CalData? var body: some View { List(caldatas, id: \.self) { eventData in Button(action: { selectedEvent = eventData handleEventSelection() }) { Text(eventData.title) } } } private func handleEventSelection() { guard selectedEvent != nil else { return } } } When I run the shortcut, gives me the following error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot insert 'CalData' in this managed object context because it is not found in the associated managed object model. I attempted to save this using SwiftData with the following model: import SwiftData @Model class CalData { var title : String var datei : Date var datef : Date var tipo : String var endereco : String @Relationship(deleteRule: .cascade) var caldataval = [CalDataVal]() var reminder: Bool = false init(title:String, datei:Date, datef:Date, tipo:String, endereco:String, reminder:Bool){ self.title = title self.datei = datei self.datef = datef self.tipo = tipo self.endereco = endereco self.reminder = reminder } } As for the second question, how can I add a parameter that can have multiple values to save them to EventDataVal, resembling a one-to-many relationship: import SwiftData @Model class CalDataVal { var name : String var value : Double init(name:String, value:Double){ self.name = name self.value = value } } Thanks in advanced
0
0
249
Apr ’24
Seeking assistance with shortcut "Run Shell Script"
Hello IOS Dev Community, I'm very new to Apple shortcuts and am on a journey to build up a series of shortcuts to make my life easier on Mac. I have Google Drive linked to Finder, then I made a program like the one below which allows me to select a destination folder in the said Drive folder and move the most recent downloaded file over. I usually start the program by typing in the spotlight search bar, but it would show this error: "ls: .: Operation not permitted" but, when I actually open the Shortcuts app and click run, it works perfectly fine, what could be the reason behind this? Thank you guys
0
0
155
Apr ’24
Seeking Assistance with Bulk Input of Pronunciation Corrections for iOS
Hello iOS Developer Community, I hope this message finds you healthy and happy. I am reaching out to seek your expertise and assistance with a particular challenge I’ve encountered while using the Speak Screen and Speak Selection features on iOS. As you may know, these features are incredibly useful for reading text aloud, but they sometimes struggle with the correct pronunciation of homographs—words that are spelled the same but have different meanings and pronunciations. An example of this is the word “live,” which can be pronounced differently based on the context of the sentence. To enhance my user experience, I am looking to input corrections for the pronunciation of “live” in its “happening now” context, such as in “live broadcast” or “live event.” However, the current process requires manual entry for each phrase, which is quite labor-intensive. I am wondering if there is a way to automate or streamline this process, perhaps through a shortcut or script that allows for bulk input of these corrections. Additionally, if anyone has already compiled a list of common phrases with homographs and their correct pronunciations, I would greatly appreciate it if you could share it or guide me on where to find such resources. Your insights and guidance on this matter would be invaluable, and I believe any solutions could benefit not just myself but many other users facing similar issues. Thank you for your time and consideration. I look forward to any suggestions or advice you may have. Best regards, Alec
0
0
227
Apr ’24
How to create AppEntity shortcut to be shown in Spotlight
I am exploring Appi-Intent and Appshortcut. We can create an action shortcut by using the following code. struct WatchListShortcut: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { AppShortcut( intent: WatchListAppIntent(), phrases: [ "Tell \(.applicationName) to open first item in watch list", ], shortTitle: "WatchList item", systemImageName: "systemimage" ) } } What I want to show an entity shortcut like shown in the below screenshot. linkText I am not sure how to create the shortcut like Assigned one in the above screen.
0
0
276
Apr ’24
scaning and saving
hi there, would someone kindly show me the syntax for the following please. I have the shortcut scan which is good but i want to save the scan to Icloud / documents / and then to a folder called scans. i somehow have the syntax wrong when in the "save" area I have Save file to Icloud drive then Subpath to the folder "scans" but this doesn't seem to work. Anyone put me in the correct direction please ? regards Nick
0
0
198
Apr ’24
Dispatch queue: com.apple.NSURLSession-delegate after executing self written shortcut
Currently I am trying to create some shortcuts for my iOS 17 app. The AppIntent looks like this: class PostClass{ public init() { let url = URL(string: "http://myurl")! var request = URLRequest(url: url) request.httpMethod = "POST" struct Message: Encodable { let device_type: String } let message = Message( device_type: "device" ) let data = try! JSONEncoder().encode(message) request.httpBody = data request.setValue( "application/json", forHTTPHeaderField: "Content-Type" ) self.request = request } } var activateDevice = PostClass() @available(iOS 17, *) struct ActivateIntent: AppIntent { static let title: LocalizedStringResource = "Activate" func perform() async throws -> some IntentResult { let task = URLSession.shared.dataTask(with: activateDevice.request) { data, response, error in let statusCode = (response as! HTTPURLResponse).statusCode if statusCode == 200 { print("SUCCESS") } else { print("FAILURE") } } task.resume() return .result() } } Unfortunately, the shortcut throws an error after every second execution. I looked into the ips-file and saw the following traceback: Thread 2 Crashed: 0 Runner 0x1028ddd30 closure #1 in ActivateIntent.perform() + 388 1 CFNetwork 0x1a6f39248 0x1a6f2a000 + 62024 2 CFNetwork 0x1a6f57210 0x1a6f2a000 + 184848 3 libdispatch.dylib 0x1adced13c _dispatch_call_block_and_release + 32 4 libdispatch.dylib 0x1adceedd4 _dispatch_client_callout + 20 5 libdispatch.dylib 0x1adcf6400 _dispatch_lane_serial_drain + 748 6 libdispatch.dylib 0x1adcf6f64 _dispatch_lane_invoke + 432 7 libdispatch.dylib 0x1add01cb4 _dispatch_root_queue_drain_deferred_wlh + 288 8 libdispatch.dylib 0x1add01528 _dispatch_workloop_worker_thread + 404 9 libsystem_pthread.dylib 0x201dd4f20 _pthread_wqthread + 288 10 libsystem_pthread.dylib 0x201dd4fc0 start_wqthread + 8 Is there any way to locate the error with these information? Has it something to do with the fact that my code is not thread-safe? Or is there any internal bug? Grateful for any help, thanks in advance!
5
0
393
Apr ’24
AppIntent Parameter Argument List of Apps
I'm currently exploring how to implement the AppIntent parameter with a list of apps similar to what's shown in the screenshots provided below: I'm particularly interested in how the searchable list of apps is implemented. My current approach involves creating an enum for the apps, but it lacks searchability and requires manual addition of each app. Does anyone have an idea on how this functionality might be implemented? It appears that the searchable list might be a native Apple view, but I haven't been able to find any documentation or resources on it. Any insights or pointers would be greatly appreciated!
1
0
296
Apr ’24
Issue with Shortcuts and relocated home folder
On macOS Sonoma (not tested with other systems) there is a bug when you have the home folder on a separate volume and you use the shortcuts apps to generate standalone programs that you can add to the dock. I found out why : those shortcuts are generated inside the Application folder that is in the home directory but when the whole home directory is not on the same volume as the system itself then you're greeted with a permission issue message. The workaround is to make a symbolic link between "external volume/home/Applications" and "main volume/home/Applications" to trick the shortcuts app into generating those standalone apps. Would be great to have this fixed.
0
0
223
Apr ’24