Integrating Siri Shortcuts into SwiftUI Apps with App Intents


Have you ever ever questioned easy methods to make your app’s options accessible from the built-in Shortcuts app on iOS? That’s what the App Intents framework is designed for. Launched in iOS 16 and macOS Ventura, the framework has been round for over two years. It gives builders with a robust technique to outline actions that customers can set off via Shortcuts. With App Intents, your app can combine seamlessly with the Shortcuts app, Siri, and even system-wide Highlight search.

On this tutorial, we’ll discover easy methods to use the App Intents framework to carry your app’s performance into Shortcuts by creating an App Shortcut. Utilizing the Ask Me Something app as our instance, we’ll stroll via the method of letting customers ask questions proper from Shortcuts.

This tutorial assumes you are accustomed to the Ask Me Something app from our Basis Fashions tutorial. If you have not learn it but, please evaluation that tutorial first.

Utilizing App Intents

The Ask Me Something app permits customers to ask questions after which it gives solutions utilizing the on-device LLM. What we’re going to do is to reveal this characteristic to the Shortcuts app. To do this, all you should do is to create a brand new Struct and undertake the App Intents framework.

Let’s create a brand new file named AskQuestionIntent within the AskMeAnything mission and replace its content material like beneath:

import SwiftUI
import AppIntents

struct AskQuestionIntent: AppIntent {
    static var title: LocalizedStringResource = "Ask Query"
    static var description = IntentDescription("Ask a query to get an AI-powered reply")
    
    static let supportedModes: IntentModes = .foreground
    
    @Parameter(title: "Query", description: "The query you need to ask")
    var query: String
    
    @AppStorage("incomingQuestion") var storedQuestion: String = ""
    
    init() {}
    
    init(query: String) {
        self.query = query
    }
    
    func carry out() async throws -> some IntentResult {
        storedQuestion = query
        
        return .end result()
    }
}

The code above defines a struct known as AskQuestionIntent, which is an App Intent utilizing the AppIntents framework. An App Intent is mainly a approach to your app to “speak” to the Shortcuts app, Siri, or Highlight. Right here, the intent’s job is to let a person ask a query and get an AI-powered reply.

On the prime, we have now two static properties: title and description. These are what the Shortcuts app or Siri will present the person once they take a look at this intent.

The supportedModes property specifies that this intent can solely run within the foreground, that means the app will open when the shortcut is executed.

The @Parameter property wrapper defines the enter the person wants to present. On this case, it is a query string. When somebody makes use of this shortcut, they will be prompted to sort or say this query.

The @AppStorage("incomingQuestion") property is a handy technique to persist the offered query in UserDefaults, making it accessible to different components of the app.

Lastly, the carry out() perform is the place the intent truly does its work. On this instance, it simply takes the query from the parameter and saves it into storedQuestion. Then it returns a .end result() to inform the system it’s finished. You’re not doing the AI name instantly right here — simply passing the query into your app so it may possibly deal with it nevertheless it desires.

Dealing with the Shortcut

Now that the shortcut is prepared, executing the “Ask Query” shortcut will routinely launch the app. To deal with this conduct, we have to make a small replace to ContentView.

First, declare a variable to retrieve the query offered by the shortcut like this:

@AppStorage("incomingQuestion") personal var incomingQuestion: String = ""

Subsequent, connect the onChange modifier to the scroll view:

ScrollView {

...


}
.onChange(of: incomingQuestion) { _, newQuestion in
    if !newQuestion.isEmpty {
        query = newQuestion
        incomingQuestion = ""
        
        Activity {
            await generateAnswer()
        }
    }
}

Within the code above, we connect an .onChange modifier to the ScrollView so the view can reply each time the incomingQuestionvalue is up to date. Contained in the closure, we verify whether or not a brand new query has been acquired from the shortcut. If that’s the case, we set off the generateAnswer() methodology, which sends the query to the on-device LLM for processing and returns an AI-generated reply.

Including a Preconfigured Shortcut

In essence, that is the way you create a shortcut that connects on to your app. In the event you’ve explored the Shortcuts app earlier than, you’ve most likely seen that many apps already present preconfigured shortcuts. For example, the Calendar app consists of ready-made shortcuts for creating and managing occasions.

Preconfigured app shortcuts

With the App Intents framework, including these preconfigured shortcuts to your individual app is easy. They can be utilized immediately within the Shortcuts app or triggered hands-free with Siri. Constructing on the AskQuestionIntent we outlined earlier, we are able to now create a corresponding shortcut so customers can set off it extra simply. For instance, right here’s how we may outline an “Ask Query” shortcut:

struct AskQuestionShortcut: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: AskQuestionIntent(),
            phrases: [
                "Ask (.applicationName) a question",
                "Ask (.applicationName) about (.applicationName)",
                "Get answer from (.applicationName)",
                "Use (.applicationName)"
            ],
            shortTitle: "Ask Query",
            systemImageName: "questionmark.bubble"
        )
    }
}

The AskQuestionShortcut adopts the AppShortcutsProvider protocol, which is how we inform the system what shortcuts our app helps. Inside, we outline a single shortcut known as “Ask Query,” which is tied to our AskQuestionIntent. We additionally present a set of instance phrases that customers would possibly say to Siri, comparable to “Ask [App Name] a query” or “Get reply from [App Name].”

Lastly, we give the shortcut a brief title and a system picture title so it’s visually recognizable contained in the Shortcuts app. As soon as this code is in place, the system routinely registers it, and customers will see the shortcut prepared to make use of—no further setup required.

Testing the Shortcut

Shortcuts in Shortcuts app and Spotlight Search

To present the shortcut a strive, construct and run the app on both the simulator or a bodily iOS gadget. As soon as the app has launched not less than as soon as, return to the Dwelling Display screen and open the Shortcuts app. You must now discover the “Ask Query” shortcut we simply created, prepared so that you can use.

The brand new shortcut not solely seems within the Shortcuts app however can be out there in Highlight search.

Whenever you run the “Ask Query” shortcut, it ought to routinely immediate you for query. When you sort your query and faucet Finished, it brings up the app and present you the reply.

shortcut-demo-homescreen.png

Abstract

On this tutorial, we explored easy methods to use the App Intents framework to reveal your app’s performance to the Shortcuts app and Siri. We walked via creating an AppIntent to deal with person enter, defining a preconfigured shortcut, and testing it proper contained in the Shortcuts app. With this setup, customers can now ask inquiries to the Ask Me Something app instantly from Shortcuts or through Siri, making the expertise sooner and extra handy.

Within the subsequent tutorial, we’ll take it a step additional by displaying you easy methods to show the AI’s reply in a Reside Exercise. This may let customers see their responses in actual time, proper on the Lock Display screen or within the Dynamic Island—with out even opening the app.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles